void CManagedSearch::Start() { if ( InterlockedCompareExchange( (LONG*)&m_bActive, TRUE, FALSE ) ) return; CQuickLock oLock( SearchManager.m_pSection ); if ( SearchManager.Add( this ) ) { m_tExecute = 0; m_tLastED2K = 0; m_tMoreResults = 0; m_nQueryCount = 0; m_pNodes.RemoveAll(); } }
inline ::LONG and ( volatile ::LONG& x, ::LONG y ) { #if defined(InterlockedAnd) return InterlockedAnd(&x, y); #else LONG i; LONG j; j = x; do { i = j; j = InterlockedCompareExchange(&x, i&y, i); } while (i != j); return j; #endif }
/*++ ClasspStopIdleTimer Routine Description: Stop the idle timer if running. Also reset the timer counters. Arguments: FdoData - Pointer to the private fdo data Return Value: None --*/ VOID ClasspStopIdleTimer( PCLASS_PRIVATE_FDO_DATA FdoData ) { LONG timerStarted; TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_TIMER, "ClasspStopIdleTimer: Stop idle timer\n")); timerStarted = InterlockedCompareExchange(&FdoData->IdleTimerStarted, 0, 1); if (timerStarted) { (VOID)KeCancelTimer(&FdoData->IdleTimer); } return; }
int git_threads_init(void) { int error = 0; /* Enter the lock */ while (InterlockedCompareExchange(&_mutex, 1, 0)) { Sleep(0); } /* Only do work on a 0 -> 1 transition of the refcount */ if (1 == git_atomic_inc(&git__n_inits)) error = synchronized_threads_init(); /* Exit the lock */ InterlockedExchange(&_mutex, 0); return error; }
static int winMutexInit(void) { /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ) { int i; for(i=0; i<ArraySize(winMutex_staticMutexes); i++) { InitializeCriticalSection(&winMutex_staticMutexes[i].mutex); } winMutex_isInit = 1; } else { /* Someone else is in the process of initing the static mutexes */ while( !winMutex_isInit ) { Sleep(1); } } return SQLITE_OK; }
gboolean mono_rand_open (void) { static gint32 status = 0; if (status != 0 || InterlockedCompareExchange (&status, 1, 0) != 0) { while (status != 2) mono_thread_info_yield (); return TRUE; } srand (time (NULL)); status = 2; return TRUE; }
void SpinMutex::lock() { for (;;) { if(InterlockedCompareExchange((LONG*)&m_id, 1, 0) == 0) { ::MemoryBarrier(); return; } while(m_id) { Sleep(0); } } }
static void ossl_init_once_run(OPENSSL_INIT_ONCE *once, void (*init)(void)) { LONG volatile *lock = (LONG *)once; LONG result; if (*lock == ONCE_DONE) return; do { result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED); if (result == ONCE_UNINITED) { init(); *lock = ONCE_DONE; return; } } while (result == ONCE_ININIT); }
VOID NTAPI WdmAudTimerRoutine( IN PDEVICE_OBJECT DeviceObject, IN PVOID Context) { PWDMAUD_DEVICE_EXTENSION DeviceExtension; /* get device extension */ DeviceExtension = (PWDMAUD_DEVICE_EXTENSION)DeviceObject->DeviceExtension; if (InterlockedCompareExchange((volatile long *)&DeviceExtension->WorkItemActive, 1, 0) == 0) { /* queue work item */ IoQueueWorkItem(DeviceExtension->WorkItem, WdmAudInitWorkerRoutine, DelayedWorkQueue, (PVOID)DeviceExtension); } }
// ****************************************************************** // * 0x0033 - InterlockedCompareExchange() // ****************************************************************** // Source:ReactOS XBSYSAPI EXPORTNUM(51) xboxkrnl::LONG FASTCALL xboxkrnl::KRNL(InterlockedCompareExchange) ( IN OUT PLONG VOLATILE Destination, IN LONG Exchange, IN LONG Comparand ) { LOG_FUNC_BEGIN LOG_FUNC_ARG(Destination) LOG_FUNC_ARG(Exchange) LOG_FUNC_ARG(Comparand) LOG_FUNC_END; LONG res = InterlockedCompareExchange((NtDll::PLONG)Destination, (NtDll::LONG)Exchange, (NtDll::LONG)Comparand); RETURN(res); }
bool pollSubStatus_MainThread(t_enum_status &outNewSubStatus) { assert(isMainThread()); bool subStatusChanged= false; // Atomically fetch the status from the WorkerThread LONG newSubStatus= InterlockedCompareExchange(&subStatus_WorkerThread, subStatus_WorkerThread, subStatus_WorkerThread); if (newSubStatus != subStatus_MainThread) { subStatus_MainThread= newSubStatus; outNewSubStatus= static_cast<t_enum_status>(newSubStatus); subStatusChanged= true; } return subStatusChanged; }
void BackupStart(TCHAR *backup_filename) { TCHAR *tm = NULL; LONG cur_state; cur_state = InterlockedCompareExchange((volatile LONG*)&m_state, 1, 0); if (cur_state != 0) { /* Backup allready in process. */ ShowPopup(TranslateT("Database back up in process..."), TranslateT("Error"), NULL); /* Show error message :) */ return; } if (backup_filename != NULL) tm = mir_tstrdup(backup_filename); if (mir_forkthread(BackupThread, (void*)tm) == INVALID_HANDLE_VALUE) { InterlockedExchange((volatile LONG*)&m_state, 0); /* Backup done. */ mir_free(tm); } }
void Lcg::setSeed(long seed) { if(isThreadSafe_) { #ifdef NIWA_RANDOM_LCG_LOCK_FREE LONG backup; do { backup = value_; } while(backup != InterlockedCompareExchange(&value_, seed, backup)); #else EnterCriticalSection(&mutex_); value_ = static_cast<unsigned int>(seed); LeaveCriticalSection(&mutex_); #endif } else { value_ = static_cast<unsigned int>(seed); } }
static gboolean threadpool_start_thread (ThreadPool *tp) { gint n; guint32 stack_size; stack_size = (!tp->is_io) ? 0 : SMALL_STACK; while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) { if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) { mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1); mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size); return TRUE; } } return FALSE; }
int VISIBLE kqueue(void) { struct kqueue *kq; struct kqueue *tmp; #ifdef _WIN32 if (InterlockedCompareExchange(&kq_init_begin, 0, 1) == 0) { libkqueue_init(); } else { while (kq_init_complete == 0) { sleep(1); } } #else (void) pthread_mutex_lock(&kq_mtx); (void) pthread_once(&kq_is_initialized, libkqueue_init); (void) pthread_mutex_unlock(&kq_mtx); #endif kq = calloc(1, sizeof(*kq)); if (kq == NULL) return (-1); tracing_mutex_init(&kq->kq_mtx, NULL); if (kqops.kqueue_init(kq) < 0) { free(kq); return (-1); } dbg_printf("created kqueue, fd=%d", kq->kq_id); tmp = map_delete(kqmap, kq->kq_id); if (tmp != NULL) { dbg_puts("FIXME -- memory leak here"); // TODO: kqops.kqueue_free(tmp), or (better yet) decrease it's refcount } if (map_insert(kqmap, kq->kq_id, kq) < 0) { dbg_puts("map insertion failed"); kqops.kqueue_free(kq); return (-1); } return (kq->kq_id); }
VOID ApsWriteLogEntry( __in ULONG ProcessId, __in APS_LOG_LEVEL Level, __in PSTR Format, ... ) { ULONG IsLogging; va_list Argument; PAPS_LOG_ENTRY Entry; CHAR Buffer[APS_LOG_TEXT_LIMIT]; // // Check whether logging's enabled // IsLogging = InterlockedCompareExchange(&ApsLogObject.Flag, 0, 0); if (!IsLogging) { return; } va_start(Argument, Format); StringCchVPrintfA(Buffer, MAX_PATH, Format, Argument); va_end(Argument); Entry = (PAPS_LOG_ENTRY)ApsMalloc(sizeof(APS_LOG_ENTRY)); Entry->ProcessId = ProcessId; Entry->Level = Level; GetLocalTime(&Entry->TimeStamp); StringCchCopyA(Entry->Text, APS_LOG_TEXT_LIMIT, Buffer); // // Queue record entry to logging queue, note that this routine can be // called concurrently, so logging object's lock must be acquired to // protect the log record queue // EnterCriticalSection(&ApsLogObject.Lock); InsertTailList(&ApsLogObject.ListHead, &Entry->ListEntry); ApsLogObject.ListDepth += 1; LeaveCriticalSection(&ApsLogObject.Lock); return; }
int x264_threading_init( void ) { LONG state; while( (state = InterlockedCompareExchange( &threading_is_init, -1, 0 )) != 0 ) { /* if already init, then do nothing */ if( state > 0 ) return 0; } if( threading_init() < 0 ) { InterlockedExchange( &threading_is_init, 0 ); return -1; } InterlockedExchange( &threading_is_init, 1 ); return 0; }
ULONG FASTCALL RtlInterlockedSetClearBits ( IN OUT PULONG Flags, IN ULONG sFlag, IN ULONG cFlag ) /*++ Routine Description: This function atomically sets and clears the specified flags in the target Arguments: Flags - Pointer to variable containing current mask. sFlag - Flags to set in target CFlag - Flags to clear in target Return Value: ULONG - Old value of mask before modification --*/ { ULONG NewFlags, OldFlags; OldFlags = *Flags; NewFlags = (OldFlags | sFlag) & ~cFlag; while (NewFlags != OldFlags) { NewFlags = InterlockedCompareExchange ((PLONG) Flags, (LONG) NewFlags, (LONG) OldFlags); if (NewFlags == OldFlags) { break; } OldFlags = NewFlags; NewFlags = (NewFlags | sFlag) & ~cFlag; } return OldFlags; }
HRESULT CUnkownReport::Uninitialize() { HRESULT hr = S_OK; if ( !InterlockedCompareExchange( &m_lInit, 0, 1 ) ) { hr = S_FALSE; goto Exit0; } m_submitList.RemoveAll(); m_reportHighList.RemoveAll(); m_reportMidList.RemoveAll(); m_reportLowList.RemoveAll(); if ( m_hNotifyReport ) { m_hNotifyReport.Close(); } if ( m_hNotifyStop ) { m_hNotifyStop.Set(); AWinRunnable::WaitExit( INFINITE ); m_hNotifyStop.Close(); } m_reportFileDB.Uninitialize(); if ( m_spiBackup ) { m_spiBackup.Release(); } m_spiBakFinder.Release(); if ( m_spiUploader ) { m_spiUploader->Uninitialize(); m_spiUploader.Release(); } Exit0: return hr; }
void WorkOnFifoFE(SWR_CONTEXT *pContext, uint32_t workerId, uint32_t &curDrawFE) { // Try to grab the next DC from the ring uint32_t drawEnqueued = GetEnqueuedDraw(pContext); while (IDComparesLess(curDrawFE, drawEnqueued)) { uint32_t dcSlot = curDrawFE % pContext->MAX_DRAWS_IN_FLIGHT; DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot]; if (pDC->isCompute || pDC->doneFE) { CompleteDrawContextInl(pContext, workerId, pDC); curDrawFE++; } else { break; } } uint32_t lastRetiredFE = curDrawFE - 1; uint32_t curDraw = curDrawFE; while (IDComparesLess(curDraw, drawEnqueued)) { uint32_t dcSlot = curDraw % pContext->MAX_DRAWS_IN_FLIGHT; DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot]; if (!pDC->isCompute && !pDC->FeLock) { if (CheckDependencyFE(pContext, pDC, lastRetiredFE)) { return; } uint32_t initial = InterlockedCompareExchange((volatile uint32_t*)&pDC->FeLock, 1, 0); if (initial == 0) { // successfully grabbed the DC, now run the FE pDC->FeWork.pfnWork(pContext, pDC, workerId, &pDC->FeWork.desc); CompleteDrawFE(pContext, workerId, pDC); } } curDraw++; } }
VOID NTAPI OcRlReleaseRemoveLockAndWait( IN POC_REMOVE_LOCK_HEADER LockHeader ) /*++ This routine is called when the client would like to delete the remove- locked resource. This routine will block until all the remove locks have completed. The caller must acquire remove lock before calling this routine and must not call OcRlReleaseRemoveLock! Multiple callers may call this routine, i.e. it is thread safe. --*/ { ASSERT( KeGetCurrentIrql() == PASSIVE_LEVEL ); ASSERT( LockHeader->ReferenceCount < OC_RL_REFERENCE_COUNT_DISTRUST_THRESHOLD ); // // mark as removed // if( FALSE == InterlockedCompareExchange( &LockHeader->Removed, TRUE, FALSE ) ){ ASSERT( LockHeader->ReferenceCount >= 0x2 ); // // decrement the counter incremented when the lock was initialized, // this is done only once, InterlockedCompareExchange protects from the // concurrent entering in this block // InterlockedDecrement( &LockHeader->ReferenceCount ); } if( (InterlockedDecrement( &LockHeader->ReferenceCount )) > 0x0 ){ ASSERT( LockHeader->ReferenceCount < OC_RL_REFERENCE_COUNT_DISTRUST_THRESHOLD ); KeWaitForSingleObject( &LockHeader->RemoveEvent, Executive, KernelMode, FALSE, NULL ); } }
/* This is the transition that signals that a thread is functioning. Its main goal is to catch threads been witnessed before been fully registered. */ void mono_threads_transition_attach (MonoThreadInfo* info) { int raw_state, cur_state, suspend_count; retry_state_change: UNWRAP_THREAD_STATE (raw_state, cur_state, suspend_count, info); switch (cur_state) { case STATE_STARTING: g_assert (suspend_count == 0); if (InterlockedCompareExchange (&info->thread_state, STATE_RUNNING, raw_state) != raw_state) goto retry_state_change; trace_state_change ("ATTACH", info, raw_state, STATE_RUNNING, 0); break; default: g_error ("Cannot transition current thread from %s with ATTACH", state_name (cur_state)); } }
ULONG ComUnknownBase::BaseTryAddRef(void) { LONG current; LONG updated; do { current = refCount_; if (current == 0u) { return 0u; } updated = current + 1; } while (InterlockedCompareExchange(&refCount_, updated, current) != current); return updated; }
BOOLEAN BtrIsCallbackComplete( IN PBTR_CALLBACK Callback, IN ULONG Count ) { ULONG i; ULONG References; for(i = 0; i < Count; i++) { References = InterlockedCompareExchange(&Callback[i].References, 0, 0); if (References != 0) { return FALSE; } } return TRUE; }
/* Wait for spin lock */ static int slwait (LOCKLONG *sl) { LOCKLONG Destination = *sl; LONG Exchange = 1; LONG Comparand = 0; #if _WIN64 while (InterlockedCompareExchange64(&Destination, Exchange, Comparand)) #else while (InterlockedCompareExchange (&Destination, Exchange, Comparand)) #endif { Sleep (0); } *sl = Destination; return 0; }
bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand ) { Assert( (size_t)pDest % 4 == 0 ); #if !(defined(_WIN64) || defined (_X360)) __asm { mov eax,comperand mov ecx,pDest mov edx,value lock cmpxchg [ecx],edx mov eax,0 setz al } #else return ( InterlockedCompareExchange( TO_INTERLOCK_PARAM(pDest), value, comperand ) == comperand ); #endif }
int git_libgit2_init(void) { int ret; /* Enter the lock */ while (InterlockedCompareExchange(&_mutex, 1, 0)) { Sleep(0); } /* Only do work on a 0 -> 1 transition of the refcount */ if ((ret = git_atomic_inc(&git__n_inits)) == 1) { if (synchronized_threads_init() < 0) ret = -1; } /* Exit the lock */ InterlockedExchange(&_mutex, 0); return ret; }
VOID NTAPI NPF_WSKCleanup( ) { TRACE_ENTER(); if (InterlockedCompareExchange(&g_SocketsState, INITIALIZED, DEINITIALIZING) != INITIALIZED) { TRACE_EXIT(); return; } WskReleaseProviderNPI(&g_WskRegistration); WskDeregister(&g_WskRegistration); InterlockedExchange(&g_SocketsState, DEINITIALIZED); TRACE_EXIT(); }
static void _lockAcquire() { LARGE_INTEGER interval; //1ms interval.QuadPart = 10000; //disable APCs KeEnterGuardedRegion(); while (LOCKED == InterlockedCompareExchange(&g_lock, LOCKED, UNLOCKED)) { //spin..with a breather.. (void)KeDelayExecutionThread(KernelMode, FALSE, &interval); } }
bool FastMutex::AttemptAcquire() { DWORD thread_id = GetCurrentThreadId(); if(thread_id == (DWORD)m_lock) { ++m_recursiveCount; return true; } DWORD owner = InterlockedCompareExchange(&m_lock, thread_id, 0); if(owner == 0) { ++m_recursiveCount; return true; } return false; }