SleepConditionVariableSRW thread optimal synchronization implementation



     1 Several key functions   

     

// conditional sleep thread  
BOOL  SleepConditionVariableSRW (  
        PCONDITION_VARIABLE ConditionVariable,  
        PSRWLOCK SRWLock,  
        DWORD dwMilliseconds,  
        ULONG Flags);  
  
// wake up a thread waiting for a condition variable  
VOID  WakeConditionVariable (PCONDITION_VARIABLE ConditionVariable);  
  
// wake up all threads waiting for condition variables  
VOID  WakeAllConditionVariable (PCONDITION_VARIABLE ConditionVariable)


 2 Example
     2.1 Three variables

     

      BOOL RUNNING=FALSE;           
      SRWLOCK g_srwlock; //Read and write synchronization objects  
      CONDITION_VARIABLE g_full; //Condition variable  
     2.2 Thread

UINT ThreadFun(LPVOID)  
{  
    AfxMessageBox(TEXT("Thread IS BEGINNING"));  
  
    /*
    1) Execute before starting the thread
    AcquireSRWLockExclusive(&g_srwlock);
    can prevent the thread from continuing to execute,
    If you want the thread to continue, just do
    ReleaseSRWLockExclusive(&g_srwlock);     
    */     
    /*
    2) Judging by Boolean variables, using conditional sleep can prevent the thread from continuing
     If you want the thread to continue, just do
     WakeAllConditionVariable(&g_full);
    */  
       AcquireSRWLockExclusive(&g_srwlock);  
  
       if (RUNNING==FALSE)   
                  SleepConditionVariableSRW(&g_full, &g_srwlock, INFINITE, 0);  
  
        AfxMessageBox(TEXT("Thread is continue"));  
  
        for(int i=0;i<100;++i) { Sleep(50);}   
  
        ReleaseSRWLockExclusive(&g_srwlock);  
  
        AfxMessageBox(TEXT("Thread IS OVER"));  
  
        return 1;  
     }  
      2.3 Start the thread and sleep

      InitializeSRWLock(&g_srwlock);  
  
      //AcquireSRWLockExclusive(&g_srwlock);  
  
      AfxBeginThread(ThreadFun,NULL);  
      2.4 Wake up the thread to continue execution

       //1)  
	//ReleaseSRWLockExclusive(&g_srwlock);  
  
	WakeAllConditionVariable(&g_full);



    





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325889295&siteId=291194637