How to create locks in VC++?

只谈情不闲聊 提交于 2019-11-29 08:42:11

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 to LeaveCriticalSection. 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.

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.

Rick

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!