|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionWith the release of Windows Vista, Microsoft introduced a new synchronization primitive called the "Condition Variable". In this article, I will explain (badly) the function of the Condition Variable and also provide a .NET wrapper. BackgroundThread synchronization can be a complex and sometimes frustrating task. I embrace anything which comes along and makes the task a little easier. Microsoft did just that, they introduced the Condition Variable. When I saw it, I said, "Awesome! can't wait to use it!". Unfortunately, the functionality is only exposed to the unmanaged world, and I work in a C# shop. So, what's a guy to do? Um.... Write a wrapper leveraging C++/CLI, expose the functionality to the .NET world, and write an article, of course! Condition Variables ExplainedSo, what are condition variables anyway? Condition Variables allow a thread to release a lock ( Using the CodeThe first thing you will notice is that the C++ project contains not one, but two classes. Given that Microsoft does not expose the "Critical Section" functionality (they do, however, provide similar functionality via the You will also notice that I named the wrapper class for the "Condition Variable" functionality, " WaitCondition waitCondition = new WaitCondition();
CriticalSection criticalSection = new CriticalSection();
//Thread 1:
criticalSection.Enter();
//in a single atomic operation, release the critical section
//and sleep (waiting for the condition variable to be signaled
waitCondition.Sleep(criticalSection);
//Thread 2: wake up Thread 1
waitCondition.WakeOne();
//Thread 1: Once awake, do something....
DoSomething();
//Exit the Critical Section
criticalSection.Exit();
//Don't forget to dispose, or leverage the 'using' statement
//to ensure that the unmanaged CRITICAL_SECTION and
//CONDITION_VARIABLE structures are properly released
waitCondition.Dispose();
criticalSection.Dispose();
Points of InterestWhile it is technically okay to use the
|
||||||||||||||||||||||