问题
Lets say I am implementing a critical section and protecting some array in VC++, how do I do it using locks in VC++?
回答1:
You need the API functions for critical sections:
- InitializeCriticalSection Call once, from any thread, but typically the main thread, to initialize the lock. Initialize before you do anything else with it.
- EnterCriticalSection Call 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.
- LeaveCriticalSection Release the lock. Each call to
EnterCriticalSection
must be paired with a matching call toLeaveCriticalSection
. Don't let exceptions stop these acquire/release calls being paired up. - DeleteCriticalSection Call 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 CCriticalSection which 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.
回答2:
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.
回答3:
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).
来源:https://stackoverflow.com/questions/5054114/how-to-create-locks-in-vc