Lets say I am implementing a critical section and protecting some array in VC++, how do I do it using locks in VC++?
How to create locks in VC++?
3.5k Views Asked by Arjun Singri At
3
There are 3 best solutions below
1
On
Create a mutex via CreateMutex, take ownership of it via WaitForSingleObject, release ownership of the mutex via ReleaseMutex, and deleted it when you are done with CloseHandle.
Alternatives you can look up include CriticalSections, Semaphores, and Events.
1
On
If you're using VS 2010, a criticial_section object is included in the header file ppl.h.
Note there is also a concurrent_vector class template which is synchronized (i.e. locks aren't needed).
You need the API functions for critical sections:
InitializeCriticalSectionCall once, from any thread, but typically the main thread, to initialize the lock. Initialize before you do anything else with it.EnterCriticalSectionCall from any thread to acquire the lock. If another thread has the lock, it will block until it can acquire the lock. Critical sections are re-entrant meaning a thread successfully acquires the lock even if it already holds it.LeaveCriticalSectionRelease the lock. Each call toEnterCriticalSectionmust be paired with a matching call toLeaveCriticalSection. Don't let exceptions stop these acquire/release calls being paired up.DeleteCriticalSectionCall once, from any thread, but typically the main thread, to finalize the lock. Do this when no threads hold the lock. After you call this the lock is invalid and you can't attempt to acquire it again.MSDN helpfully provide a trivial example.
If you are using MFC then you would probably use
CCriticalSectionwhich wraps up the Win32 critical section APIs in a class.As for how you do it with your array. Well, your threads will only execute blocks of code protected by the lock one at a time. You need the lock to stop race conditions where two threads try to read/write to the same memory location simultaneously, or indeed other more subtle conditions that can break your algorithm.
If you were to describe the array, its contents, and how you operate on it, then it might be possible to give you some specific advice. Exactly how you operate on this array will have a large bearing on the ideal synchronisation strategy, and in certain cases you may be able to use lock-free methods.