具体见:
http://blog.csdn.net/theplayerwuliang/article/details/6431722
复制代码可运行:
1 #pragma once 2 #include "stdafx.h" 3 #include < windows.h > 4 //class InstanceLock; 5 class InstanceLockBase 6 { 7 friend class InstanceLock; 8 CRITICAL_SECTION cs; 9 void Lock() 10 { 11 ::EnterCriticalSection( & cs); 12 } 13 void Unlock() 14 { 15 ::LeaveCriticalSection( & cs); 16 } 17 protected : 18 InstanceLockBase() 19 { 20 ::InitializeCriticalSection( & cs); 21 } 22 ~ InstanceLockBase() 23 { 24 ::DeleteCriticalSection( & cs); 25 } 26 } ; 27 class InstanceLock 28 { 29 InstanceLockBase * _pObj; 30 public : 31 InstanceLock(InstanceLockBase * pObj) 32 { 33 _pObj = pObj; 34 if (NULL != _pObj) 35 _pObj -> Lock(); 36 } 37 ~ InstanceLock() 38 { 39 if (NULL != _pObj) 40 _pObj -> Unlock(); 41 } 42 } ; 43 44 void Say( char * text) 45 { 46 static int count = 0 ; 47 SYSTEMTIME st; 48 ::GetLocalTime( & st); 49 printf( " %03d [%02d:%02d:%02d.%03d]%s " , ++ count, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, text); 50 } 51 52 class MyClass: public InstanceLockBase 53 {} ; 54 MyClass mc; 55 56 DWORD CALLBACK ThreadProc(LPVOID param) 57 { 58 InstanceLock il( & mc); 59 Say( " in sub thread, lock " ); 60 Sleep( 2000 ); 61 Say( " in sub thread, unlock " ); 62 return 0 ; 63 } 64 65 66 67 int main() 68 { 69 while(1) 70 { CreateThread( 0 , 0 , ThreadProc, 0 , 0 , 0 ); 71 InstanceLock il( & mc); 72 Say( " in main thread, lock " ); 73 Sleep( 3000 ); 74 Say( " in main thread, unlock " ); 75 } 76 77 return 0; 78 }