void ClientCursor::staticYield(int micros, const StringData& ns, const Record* rec) { bool haveReadLock = Lock::isReadLocked(); killCurrentOp.checkForInterrupt( false ); { auto_ptr<LockMongoFilesShared> lk; if ( rec ) { // need to lock this else rec->touch won't be safe file could disappear lk.reset( new LockMongoFilesShared() ); } dbtempreleasecond unlock; if ( unlock.unlocked() ) { if ( haveReadLock ) { // This sleep helps reader threads yield to writer threads. // Without this, the underlying reader/writer lock implementations // are not sufficiently writer-greedy. #ifdef _WIN32 SwitchToThread(); #else if ( micros == 0 ) { yieldOrSleepFor1Microsecond(); } else { sleepmicros(1); } #endif } else { if ( micros == -1 ) { sleepmicros(Client::recommendedYieldMicros()); } else if ( micros == 0 ) { yieldOrSleepFor1Microsecond(); } else if ( micros > 0 ) { sleepmicros( micros ); } } } else if ( Listener::getTimeTracker() == 0 ) { // we aren't running a server, so likely a repair, so don't complain } else { CurOp * c = cc().curop(); while ( c->parent() ) c = c->parent(); warning() << "ClientCursor::yield can't unlock b/c of recursive lock" << " ns: " << ns << " top: " << c->info() << endl; } if ( rec ) rec->touch(); lk.reset(0); // need to release this before dbtempreleasecond } }
void CStressManager::DisconnectAll() { Zion::Map<_U32, CStressClient*>::iterator i; _U32 count = 1; while(count>0) { count = 0; A_MUTEX_LOCK(&m_mtxLocker); for(i=m_mapClients.begin(); i!=m_mapClients.end(); i++) { i->second->Logout(); if(i->second->GetClient()->GetState()!=CClient::STATE_NA && i->second->GetClient()->GetState()!=CClient::STATE_FAILED) count++; } A_MUTEX_UNLOCK(&m_mtxLocker); SwitchToThread(); if(!CClientApp::GetDefault()->IsThread()) { CClientApp::GetDefault()->Tick(); } } for(i=m_mapClients.begin(); i!=m_mapClients.end(); i++) { delete i->second; } m_mapClients.clear(); }
static int initWinSock(void) { WORD wVersionRequested; WSADATA wsaData; int i; static LONG volatile initialized = 0; wVersionRequested = MAKEWORD(1, 1); if (InterlockedCompareExchange((LPLONG) &initialized,1L,0L) == 0L) { /* FIXME not terminate, just a message?! */ if ((i = WSAStartup(wVersionRequested, &wsaData))) { EI_TRACE_ERR1("ei_connect_init", "ERROR: can't initialize windows sockets: %d",i); initialized = 2L; return 0; } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { EI_TRACE_ERR0("initWinSock","ERROR: this version of windows " "sockets not supported"); WSACleanup(); initialized = 2L; return 0; } initialized = 3L; } else while (initialized < 2) { SwitchToThread(); } return (int) (initialized - 2); }
static __inline void fast_enter_critical_section(struct threadpool *tp) { sync_t *sync = (sync_t *) tp; while (!TryEnterCriticalSection(&sync->critsec)) SwitchToThread(); }
void rathread_yield(){ #ifdef WIN32 SwitchToThread(); #else sched_yield(); #endif }//end: rathread_yield()
void CBufferOutputAudioEngine::Play() { //BufferTrace("CBufferOutputAudioEngine::Play()....\n"); if (!m_bFilled && m_mapOutputAudioBuf.size() < (1.0f*BUFFER_PERSEC_AUDIO_NUMBER*BUFFER_OUTPUT_ONMIC_AUDIO_MAX_LIMIT)/1000){ return ; } if (!m_bFilled) { m_fLastPlayTime = GetTickCount(); m_iStartPlayCount = 0; m_bFilled = true; } if (m_mapOutputAudioBuf.size() < 1 || (GetTickCount() - m_lastRecvTime) > 1000*10){//10s钟没有收到数据 超时 刷新 MutexLocker locker(&m_mutex);//播放线程 网络线程 m_mapOutputAudioBuf ResetStatus(); return; } IsCanCalcRecvRate()?m_fRecvRate = CalcRecevRate():NULL; m_fSendRate = CanCalcPlayRate(); //ErrTrace("CBufferOutputAudioEngine::Play() m_mapOutputAudioBuf.size()=%d,seq=%d,m_fRecvRate=%f,m_fSendRate=%f\n",m_mapOutputAudioBuf.size(),m_iMaxSequenceId - m_iMinSequenceId+1,m_fRecvRate,m_fSendRate); unsigned int iLimit = 0; DWORD dwCurrTime = GetTickCount(); while (m_fLastPlayTime < dwCurrTime && ++iLimit<5) { m_fLastPlayTime += m_fSendRate; m_iStartPlayCount++; PlayPackets(); SwitchToThread(); } CheckPacket(); RefreshStatus(); }
BOOL StopIoTimer(LPTIMER lpTimer, BOOL bSkipActive) { // Sanity check if (!lpTimer) return 0; for (;;) { switch (InterlockedExchange(&lpTimer->lStatus, TIMER_CANCEL)) { case TIMER_CANCEL: case TIMER_ACTIVE: // Timer procedure is currently active if (bSkipActive) return -1; SwitchToThread(); break; case TIMER_WAIT: // Timer is in wait state EnterCriticalSection(&csIoTimer); // Remove timer if it has not been posted if (lpTimer->lStatus != TIMER_QUEUED) DeleteIoTimer(lpTimer); LeaveCriticalSection(&csIoTimer); Free(lpTimer); return 0; case TIMER_INACTIVE: // Timer is inactive Free(lpTimer); return 1; case TIMER_QUEUED: return 0; } } }
SO_PUBLIC void Thread_Yield(void) { #ifdef _MSC_VER SwitchToThread(); #else pthread_yield(); #endif }
static void os_yield(void) { #if defined(WIN32) SwitchToThread(); #else sched_yield(); #endif }
/* * ------------------------------------------------------------------- * Allow another thread to execute. If no other threads are runable this * is not guarenteed to actually rest. * ------------------------------------------------------------------- */ void thread_rest ( void ) { #if defined( HAVE_THREAD ) #if defined( HAVE_POSIX_THREAD ) #else // Win32 SwitchToThread( ); #endif #endif }
teUtilsStatus eUtils_ThreadYield(void) { #ifndef WIN32 sched_yield(); #else SwitchToThread(); #endif return E_UTILS_OK; }
void yieldOrSleepFor1Microsecond() { #ifdef _WIN32 SwitchToThread(); #elif defined(__linux__) pthread_yield(); #else sleepmicros(1); #endif }
int sched_yield() { /* http://stackoverflow.com/questions/1383943/switchtothread-vs-sleep1 SwitchToThread(); was here. Unsure what's better for us, just trying.. */ if(!SwitchToThread()) Sleep(0); return 0; }
//The functions below should thread the while loop static UINT bg1(LPVOID that) { while (*lenref == 0) SwitchToThread();//sync (by using another long * as a temp) fileDefault = CString(buff); if (FileOpen(false)) { run((CKODEKDlg *)that, ACTION_DECOMPRESS); return 0; } run((CKODEKDlg *)that, END); return -1; }
VOID WINAPI DoWaitForReaders(IN PWAH_SEARCH_TABLE Table, IN PVLONG Counter) { HANDLE EventHandle; /* Do a context switch */ SwitchToThread(); /* Check if the counter is above one */ if (*Counter > 0) { /* * This shouldn't happen unless priorities are messed up. Do a wait so * that the threads with lower priority will get their chance now. */ if (!ghWriterEvent) { /* We don't even have an event! Allocate one manually... */ EventHandle = CreateEvent(NULL, TRUE, FALSE, NULL); if (EventHandle) { /* Save the event handle atomically */ if ((InterlockedCompareExchangePointer((PVOID*)&ghWriterEvent, EventHandle, NULL))) { /* Someone beat us to it, close ours */ CloseHandle(EventHandle); } } else { /* Things couldn't get worse for us. Do a last-resort hack */ while (*Counter > 0) Sleep(10); } } /* * Our event is ready. Tell the others to signal us by making sure * that the last counter will be -1, notifying the last thread of our * request. */ if (InterlockedDecrement(Counter) >= 0) { /* Keep looping */ do { /* Wait in tiny bursts, so we can catch the PulseEvent */ WaitForSingleObject(ghWriterEvent, 10); } while (*Counter >= 0); } } }
void WaitForWriteCapacity(int amt) { for (; ; ) { //dont return when available == amt because then we would consume the buffer and be unable to distinguish between full and empty if (Available() > amt) return; //this is a greedy spinlock. SwitchToThread(); } }
/* * ------------------------------------------------------------------- * Allow another thread to execute. If no other threads are runable this * is not guarenteed to actually rest. * ------------------------------------------------------------------- */ void thread_rest ( void ) { #if defined( HAVE_THREAD ) #if defined( HAVE_POSIX_THREAD ) // TODO add checks for sched_yield or pthread_yield and call that // if available usleep( 0 ); #else // Win32 SwitchToThread( ); #endif #endif }
void sys_thread_switch (struct sys_thread *td) { sys_vm2_leave(td); #ifndef _WIN32 sched_yield(); #else SwitchToThread(); #endif sys_vm2_enter(td); }
bool Tick() { bool DoNextTick = true; DoNextTick = TickSim(); TickRender(); SwitchToThread(); return DoNextTick; }
void rtw_yield_os() { #ifdef PLATFORM_LINUX yield(); #endif #ifdef PLATFORM_FREEBSD yield(); #endif #ifdef PLATFORM_WINDOWS SwitchToThread(); #endif }
/** * \ingroup atomvm * \b atomvmCtrlIntRequest * * This is an atomvm controll function used by a controlling thread(s) * and must not be called from the atom virtual machine. * * This function requests an interrupt service routine to be called in the * context of the atom virtual machine. * * The call will block while a previously scheduled interrupt is in progress. * * @param[in] atomvm Handle to the virtual machine created by atomvmCtrlInit. * @param[in] isr The address of the interrupt service routine. The routine must use * the default calling convention of the compiler. * * @return None */ void atomvmCtrlIntRequest (HATOMVM atomvm, uint32_t isr) { PATOMVM patomvm = (PATOMVM) atomvm ; WaitForSingleObject (patomvm->atomvm_int_complete, INFINITE) ; while (InterlockedCompareExchange ((volatile uint32_t *)&patomvm->isr, isr, 0) != 0) { SwitchToThread() ; } SetEvent (patomvm->atomvm_int) ; }
// Yield processing time to other threads inline static void Yield () { #ifdef _WIN32 # if AX_ASYNC_MSWIN_SWITCHTOTHREAD_ENABLED SwitchToThread(); # else Sleep( 0 ); # endif #else sched_yield(); #endif }
/** * Once-only initialization. * @param once_control The control variable which initialized to PTHREAD_ONCE_INIT. * @param init_routine The initialization code which executed at most once. * @return Always return 0. */ int pthread_once(pthread_once_t *once_control, void (* init_routine)(void)) { if (atomic_cmpxchg((long volatile *) once_control, 1, 0) == 0) { init_routine(); *(volatile int *) once_control = 2; } else { while(*(volatile int *) once_control != 2) SwitchToThread(); } return 0; }
bool Launch( SimpleString& CommandLine ) { if( g_NumWarnings > 0 ) { AddStatus( SimpleString::PrintF( "\nContentSyncer finished with %d warnings.\n\nPress Enter to continue.", g_NumWarnings ), g_StatusColor ); // Mini loop in here, ugh! for(;;) { g_Keyboard->Tick( 0.0f ); if( GetForegroundWindow() == GetConsoleWindow() ) { if( g_Keyboard->OnRise( Keyboard::EB_Enter ) ) { break; } } TickRender(); SwitchToThread(); } } STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo; ZeroMemory( &StartupInfo, sizeof( StartupInfo ) ); StartupInfo.cb = sizeof( StartupInfo ); ZeroMemory( &ProcessInfo, sizeof( ProcessInfo ) ); // See Process Creation Flags DWORD Flags = CREATE_DEFAULT_ERROR_MODE | // Don't inherit error mode CREATE_NEW_CONSOLE; // Create new console (DETACHED_PROCESS also means this console isn't inherited; but a new console must be created with AllocConsole) BOOL Result = CreateProcess( NULL, // Application name (optional--use the first argument from command line if NULL) CommandLine.MutableCStr(), // Command line (optional, includes application name) NULL, // Process attributes (optional pointer to a SECURITY_ATTRIBUTES) NULL, // Thread attributes (optional pointer to a SECURITY_ATTRIBUTES) FALSE, // Inherit handles Flags, // Creation flags (see Process Creation Flags) NULL, // Environment block (optional void*) NULL, // Current directory (optional string) &StartupInfo, // Startup info &ProcessInfo // Process info ); return Result == TRUE; }
/* * __wt_yield -- * Yield the thread of control. */ void __wt_yield(void) { /* * Yielding the processor isn't documented as a memory barrier, and it's * a reasonable expectation to have. There's no reason not to explicitly * include a barrier since we're giving up the CPU, and ensures callers * aren't ever surprised. */ WT_FULL_BARRIER(); SwitchToThread(); }
static DWORD WINAPI Work(PVOID args){ Times = GetTickCount(); while(i++<1000000){ SwitchToThread(); } Total += GetTickCount() - Times; _tprintf(_T("1 000 000 Context Switch in diferent process %.5f ms\n"),Total/1000000); return 0; }
int WaitForSomethingToRead() { for (; ; ) { int available = Size(); if (available > 0) return available; //this is a greedy spinlock. SwitchToThread(); //NOTE: it's annoying right now because libsnes processes die and eat a whole core. //we need to gracefully exit somehow } }
void flext::Sleep(double s) { if(s <= 0) return; #if FLEXT_OS == FLEXT_OS_WIN #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x400 #if 0 LARGE_INTEGER liDueTime; liDueTime.QuadPart = (LONGLONG)(-1.e7*s); // Create a waitable timer. HANDLE hTimer = CreateWaitableTimer(NULL,TRUE,NULL); if(hTimer) { if(SetWaitableTimer(hTimer,&liDueTime,0,NULL,NULL,0)) // Wait for the timer. WaitForSingleObject(hTimer,INFINITE); // != WAIT_OBJECT_0) else ::Sleep((long)(s*1000.)); CloseHandle(hTimer); } else #else LARGE_INTEGER cnt; if(perffrq && QueryPerformanceCounter(&cnt)) { LONGLONG dst = (LONGLONG)(cnt.QuadPart+perffrq*s); for(;;) { SwitchToThread(); // while waiting switch to another thread QueryPerformanceCounter(&cnt); if(cnt.QuadPart > dst) break; } } else #endif #endif // last resort.... ::Sleep((long)(s*1000.)); #elif FLEXT_OS == FLEXT_OS_LINUX || FLEXT_OS == FLEXT_OS_IRIX || FLEXT_OSAPI == FLEXT_OSAPI_MAC_MACH // POSIX usleep((long)(s*1000000.)); #elif FLEXT_OS == FLEXT_OS_MAC // that's just for OS9 & Carbon! UnsignedWide tick; Microseconds(&tick); double target = tick.hi*((double)(1L<<((sizeof tick.lo)*4))*(double)(1L<<((sizeof tick.lo)*4)))+tick.lo+s*1.e6; for(;;) { // this is just a loop running until the time has passed - stone age (but we yield at least) Microseconds(&tick); if(target <= tick.hi*((double)(1L<<((sizeof tick.lo)*4))*(double)(1L<<((sizeof tick.lo)*4)))+tick.lo) break; YieldToAnyThread(); // yielding surely reduces the timing precision (but we're civilized) } #else #error Not implemented #endif }
BOOL rdp_recv_deactivate_all(rdpRdp* rdp, wStream* s) { UINT16 lengthSourceDescriptor; if (rdp->state == CONNECTION_STATE_ACTIVE) rdp->deactivation_reactivation = TRUE; else rdp->deactivation_reactivation = FALSE; /* * Windows XP can send short DEACTIVATE_ALL PDU that doesn't contain * the following fields. */ if (Stream_GetRemainingLength(s) > 0) { do { if (Stream_GetRemainingLength(s) < 4) break; Stream_Read_UINT32(s, rdp->settings->ShareId); /* shareId (4 bytes) */ if (Stream_GetRemainingLength(s) < 2) break; Stream_Read_UINT16(s, lengthSourceDescriptor); /* lengthSourceDescriptor (2 bytes) */ if (Stream_GetRemainingLength(s) < lengthSourceDescriptor) break; Stream_Seek(s, lengthSourceDescriptor); /* sourceDescriptor (should be 0x00) */ } while (0); } rdp_client_transition_to_state(rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE); while (rdp->state != CONNECTION_STATE_ACTIVE) { if (rdp_check_fds(rdp) < 0) return FALSE; if (freerdp_shall_disconnect(rdp->instance)) break; SwitchToThread(); } return TRUE; }
/* * ------------------------------------------------------------------- * Allow another thread to execute. If no other threads are runable this * is not guarenteed to actually rest. * ------------------------------------------------------------------- */ void thread_rest ( void ) { #if defined( HAVE_THREAD ) #if defined( HAVE_POSIX_THREAD ) #if defined( _POSIX_PRIORITY_SCHEDULING ) sched_yield(); #else usleep( 0 ); #endif #else // Win32 SwitchToThread( ); #endif #endif }