C, C++

Threads and Critical Sections in C/C++


Initializes a critical section object and sets the spin count for the critical section. When a thread tries to acquire a critical section that is locked, the thread spins: it enters a loop which iterates spin count times, checking to see if the lock is released. If the lock is not released before the loop finishes, the thread goes to sleep to wait for the lock to be released.


Initializes a critical section object.


Initializes a critical section object with a spin count and optional flags.


Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.


Releases ownership of the specified critical section object.


Releases all resources used by an unowned critical section object.


Creates a thread to execute within the virtual address space of the calling process.

Critical Section Objects

A critical section object provides synchronization similar to that provided by a mutex object, except that a critical section can be used only by the threads of a single process. Event, mutex, and semaphore objects can also be used in a single-process application, but critical section objects provide a slightly faster, more efficient mechanism for mutual-exclusion synchronization (a processor-specific test and set instruction). Like a mutex object, a critical section object can be owned by only one thread at a time, which makes it useful for protecting a shared resource from simultaneous access. Unlike a mutex object, there is no way to tell whether a critical section has been abandoned.


int main( void )
    HANDLE  MyHandle;
    DWORD   MyThreadIdArray[MAX_THREADS];
    int     MyThreadData = 10;
    if (!InitializeCriticalSectionAndSpinCount(&MyCriticalSection, 0x00000400) ) 
        return -1;
    MyHandle = CreateThread(NULL, 0, MyThreadFunction, &MyThreadData , 0, &MyThreadIdArray[i]);
DWORD WINAPI MyThreadFunction( LPVOID lpParameter )
    return 1;