C ++ thread synchronization of critical section

#include <the iostream> 
#include <WINDOWS.H>
 the using  namespace STD; 

the CRITICAL_SECTION CS; 

// when it is initialized to LockCount value of -1, 0 greater than or equal to this value, this indicates the critical zone is occupied; waiting to acquire critical sections threads: LockCount - (RecursionCount -1)        
 // RecursionCount this field contains the number of the owner thread has received critical section
 // OwningThread this field contains the thread in this critical area currently occupied by the thread identifier, this thread ID and the GetCurrentThreadId returning the same ID 



DWORD WINAPI ThreadProc1 (LPVOID lpParameter) 
{ 
    for ( int X = 0 ; X < 1000 ; X ++ ) 
    { 
        the EnterCriticalSection ( & CS); 
        Sleep ( 1000 ); 
        the printf ("11111:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
        LeaveCriticalSection(&cs);
    }
    return 0;
}

DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
    for (int x = 0; x < 1000; x++)
    {
        EnterCriticalSection(&cs);
        Sleep(1000);
        printf("22222:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
        LeaveCriticalSection(&cs);
    }
    return 0;
}

DWORD WINAPI ThreadProc3(LPVOID lpParameter)
{
    for (int x = 0; x < 1000; x++)
    {
        EnterCriticalSection(&cs);
        Sleep(1000);
        printf("33333:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread);
        LeaveCriticalSection(&cs);
    }
    return 0;
}

DWORD WINAPI ThreadProc4(LPVOID lpParameter)
{
    for (int x = 0 ; X < 1000 ; X ++ ) 
    { 
        the EnterCriticalSection ( & CS); 
        Sleep ( 1000 ); 
        the printf ( " 44444:% X% X% X \ n- " , cs.LockCount, cs.RecursionCount, cs.OwningThread); 
        LeaveCriticalSection ( & CS); 
    } 
    return  0 ; 
} 

int main () 
{ 
    // initialization critical section 
    InitializeCriticalSection (& CS);
     // the printf ( "% X% X% X", cs.LockCount, cs.RecursionCount, cs.OwningThread) ;
     // create a new thread 
    HANDLE CreateThread hTread1 = ( 0 , 0 , ThreadProc1, 0 , 0 , 0 );
     // create a new thread 
    HANDLE CreateThread hTread2 = ( 0 , 0 , ThreadProc2, 0 , 0 , 0 );
     // create a new thread 
    HANDLE CreateThread hTread3 = ( 0 , 0 , ThreadProc3, 0 , 0 , 0 );
     // create a new thread 
    HANDLE CreateThread hTread4 = ( 0 , 0, ThreadProc4, 0 , 0 , 0 );
     // if no other references to the place it close the handle 
    :: the CloseHandle (hTread1); 
    :: (hTread2) the CloseHandle; 
    :: (hTread3) the CloseHandle; 
    :: (hTread4 the CloseHandle); 
    // destroy the critical region
     // DeleteCriticalSection (& CS); 
    getchar ();
     return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/duxie/p/11110231.html