I need a simple ‘one at a time’ lock on a section of code. Consider the function func which can be run from multiple threads:
void func() { // locking/mutex statement goes here operation1(); operation2(); // corresponding unlock goes here operation3(); }
I need to make sure that operation1 and operation2 always run ‘together’. With C# I would use a simple lock block around these two calls. What is the C++/Win32/MFC equivalent?
Presumably some sort of Mutex?
Critical sections will work (they’re lighter-weight that mutexes.) InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, and DeleteCriticalSection are the functions to look for on MSDN.
EDIT: Critical sections are faster than mutexes since critical sections are primarily user mode primitives – in the case of an uncontended acquire (usually the common case) there is no system call into the kernel, and acquiring takes on the order of dozens of cycles. A kernel switch is more more expensive (on the order of hundreds of cycles). The only time critical sections call into the kernel is in order to block, which involves waiting on a kernel primitive, (either mutex or event). Acquiring a mutex always involves a call into the kernel, and is thus orders of magnitude slower. However, critical sections can only be used to synchronize resources in one process. In order to synchronize across multiple processes, a mutex is needed.