Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

windows - How to create locks in VC++?

Lets say I am implementing a critical section and protecting some array in VC++, how do I do it using locks in VC++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...