扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
// 全局: struct MyStruct ... { int a, b; } ; MyStruct s; // 线程1: int a = s.a; int b = s.b; // 线程2: s.a ++ ; s.b -- ; |
int a = s.a; //线程1 s.a++; //线程2 s.b++; //线程2 int b = s.b; //线程1 |
// 全局: CRITICAL_SECTION cs; InitializeCriticalSection( & cs); // 线程1: EnterCriticalSection( & cs); int a = s.a; int b = s.b; LeaveCriticalSection( & cs); // 线程2: EnterCriticalSection( & cs); s.a ++ ; s.b -- ; LeaveCriticalSection( & cs); // 最后: DeleteCriticalSection( & cs); |
class InstanceLockBase ... { CRITICAL_SECTION cs; protected : InstanceLockBase() ... { InitialCriticalSection( & cs); } ~ InstanceLockBase() ... { DeleteCriticalSection( & cs); } } ; |
struct MyStruct: public InstanceLockBase ... { … } ; |
class InstanceLockBase ... { CRITICAL_SECTION cs; void Lock() ... { EnterCriticalSection( & cs); } void Unlock() ... { LeaveCriticalSection( & cs); } … } ; |
class InstanceLock ... { InstanceLockBase * _pObj; public : InstanceLock(InstanceLockBase * pObj) ... { _pObj = pObj; // 这里会保存一份指向s的指针,用于解锁 if (NULL != _pObj) _pObj -> Lock(); // 这里加锁 } ~ InstanceLock() ... { if (NULL != _pObj) _pObj -> Unlock(); // 这里解锁 } } ; |
class InstanceLockBase ... { friend class InstanceLock; … } ; |
void ModifyS() ... { InstanceLock lock ( & s); // 这里已经实现加锁了 // some operations on s } // 一旦离开lock对象的作用域,自动解锁 |
… ... { InstanceLock lock ( & s); // do something … } … |
void Say( char * text) ... { static int count = 0 ; SYSTEMTIME st; ::GetLocalTime( & st); printf( " %03d [%02d:%02d:%02d.%03d]%s " , ++ count, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, text); } |
class MyClass: public InstanceLockBase ... {} ; MyClass mc; |
DWORD CALLBACK ThreadProc(LPVOID param) ... { InstanceLock il( & mc); Say( " in sub thread, lock " ); Sleep( 2000 ); Say( " in sub thread, unlock " ); return 0 ; } |
CreateThread( 0 , 0 , ThreadProc, 0 , 0 , 0 ); ... { InstanceLock il( & mc); Say( " in main thread, lock " ); Sleep( 3000 ); Say( " in main thread, lock " ); } |
001 [13:43:23.781]in main thread, lock 002 [13:43:26.781]in main thread, lock 003 [13:43:26.781]in sub thread, lock 004 [13:43:28.781]in sub thread, unlock |
#pragma once #include < windows.h > class InstanceLock; class InstanceLockBase ... { friend class InstanceLock; CRITICAL_SECTION cs; void Lock() ... { ::EnterCriticalSection( & cs); } void Unlock() ... { ::LeaveCriticalSection( & cs); } protected : InstanceLockBase() ... { ::InitializeCriticalSection( & cs); } ~ InstanceLockBase() ... { ::DeleteCriticalSection( & cs); } } ; class InstanceLock ... { InstanceLockBase * _pObj; public : InstanceLock(InstanceLockBase * pObj) ... { _pObj = pObj; if (NULL != _pObj) _pObj -> Lock(); } ~ InstanceLock() ... { if (NULL != _pObj) _pObj -> Unlock(); } } ; |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者