   CCriticalSection usage and behaviour
  Hi,I am trying to use a CCriticalSection object to regulate access to my API between 2 threads. One particularity is that some given API functions can call other API functions, so I need to keep track of the "locking-level" (one thread can generate nested locks, but when it exits each API function, the nested locks have to be also released). However my first question is:- Before using CCriticalSection, I tried implementing the locking mechanism myself with some apiLockLevel variable, currentThreadIDThatLockedTheAPI variable, and some while (apiLockLevel!=0) Sleep(1). This appears to me terribly inefficient because the threads spend a lot of time sleeping. Am I right in the assumption that CCriticalSection, instead of sleeping, will simply give the control (or more execution time) to the other threads?My next question is:- How can I implement nested locks using CCriticalSection? My solution is following but sometimes deadlocks:void startAPIProcedure(){DWORD tID=GetCurrentThreadId();if (idOfLockingThread==tID)apiLocked++;else{cs.Lock();idOfLockingThread=tID;apiLocked++;}}void endAPIProcedure(){apiLocked--;if (apiLocked==0){cs.Unlock();idOfLockingThread=0;}}
  Well I found the stupid bug in my code: moving the instruction "idOfLockingThread=0;" above the "cs.Unlock();" solved my deadlock problem. But is my solution efficient/safe?   ;  I don't think you need to go to all that trouble. You can enter a critical section twice without any problems, as long as you exit it twice too. At least you can when using the standard EnterCriticalSection() and LeaveCriticalSection() functions. See http://msdn.microsoft.com/en-us/library/ms682608(VS.85).aspxAlso note that in release mode the compiler could reorder those variable assignments/increments/decrements to the wrong side of the critical section call, unless you declare them volatile.   ;  Probably the easiest way to institute critical section locks is to create a smart pointer, and overload the "->" operator so it throws a critical section whenever a member variable or member function is exectued. These work very well and are very transparent to the code.  When this sychronized pointer is now used, and you have set two or more of them to the same object from different threads, simply accessing the member of the object will lock it for the access duration. 