SleepConditionVariableSRW线程最佳同步实现



     1  几个关键函数   

     

//条件休眠线程  
BOOL  SleepConditionVariableSRW (  
        PCONDITION_VARIABLE ConditionVariable,  
        PSRWLOCK SRWLock,  
        DWORD dwMilliseconds,  
        ULONG Flags);  
  
// 唤醒一个等待条件变量的线程  
VOID  WakeConditionVariable (PCONDITION_VARIABLE ConditionVariable);  
  
// 唤醒所有等待条件变量的线程  
VOID  WakeAllConditionVariable (PCONDITION_VARIABLE ConditionVariable)


 2  样例
     2.1  三个变量

     

      BOOL RUNNING=FALSE;           
      SRWLOCK  g_srwlock;         //读写同步对象  
      CONDITION_VARIABLE g_full;  //条件变量  
     2.2  线程

UINT ThreadFun(LPVOID)  
{  
    AfxMessageBox(TEXT("Thread IS BEGINNING"));  
  
    /* 
    1)启动线程前执行 
    AcquireSRWLockExclusive(&g_srwlock); 
    可以阻止线程继续执行, 
    如果想让线程继续,只需执行 
    ReleaseSRWLockExclusive(&g_srwlock);     
    */     
    /* 
    2)通过布尔变量判断,利用条件休眠可以阻止线程继续 
     如果想让线程继续,只需执行 
     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  启动线程并休眠

      InitializeSRWLock(&g_srwlock);  
  
      //AcquireSRWLockExclusive(&g_srwlock);  
  
      AfxBeginThread(ThreadFun,NULL);  
      2.4  唤醒线程继续执行

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



    





你可能感兴趣的:(c/c++/vc)