wetwoo的小窝
wetwoo的小窝

导航

<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
统计
  • 随笔 - 22
  • 文章 - 4
  • 评论 - 14
  • 引用 - 0

留言簿(1)

随笔档案

文章档案

相册

搜索

最新评论

阅读排行榜

评论排行榜

Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes.


Condition variables enable threads to atomically release a lock and enter the sleeping state. They can be used with critical sections or slim reader/writer (SRW) locks. Condition variables support operations that "wake one" or "wake all" waiting threads. After a thread is woken, it re-acquires the lock it released when the thread entered the sleeping state.

The following pseudocode demonstrates the typical usage pattern of condition variables.


CRITICAL_SECTION CritSection;
CONDITION_VARIABLE ConditionVar;

void PerformOperationOnSharedData()
{
EnterCriticalSection(&CritSection);

// Wait until the predicate is TRUE

while( TestPredicate() == FALSE )
{
SleepConditionVariableCS(&ConditionVar, &CritSection, INFINITE);
}

// The data can be changed safely because we own the critical
// section and the predicate is TRUE

ChangeSharedData();

LeaveCriticalSection(&CritSection);

// If necessary, signal the condition variable by calling
// WakeConditionVariable or WakeAllConditionVariable so other
// threads can wake
}

For example, in an implementation of a reader/writer lock, the TestPredicate function would verify that the current lock request is compatible with the existing owners. If it is, acquire the lock; otherwise, sleep. For a more detailed example, see Using Condition Variables.

Condition variables are subject to spurious wakeups (those not associated with an explicit wake) and stolen wakeups (another thread manages to run before the woken thread). Therefore, you should recheck a predicate (typically in a while loop) after a sleep operation returns.

You can wake other threads using WakeConditionVariable or WakeAllConditionVariable either inside or outside the lock associated with the condition variable. It is usually better to release the lock before waking other threads to reduce the number of context switches.

It is often convenient to use more than one condition variable with the same lock. For example, an implementation of a reader/writer lock might use a single critical section but separate condition variables for readers and writers.

posted on 2008-10-21 12:30 wetwoo的小窝 阅读(311) 评论(0)  编辑 收藏
Comments
标题  
姓名  
主页
验证码 *
内容   
  登录  使用高级评论  Top
[使用Ctrl+Enter键可以直接提交]