等待线程,直到发生条件 [英] waiting thread until a condition has been occurred

查看:190
本文介绍了等待线程,直到发生条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想等待在同时模拟器中执行的一个线程的2个线程,直到发生一个条件,可能是在模拟器中运行一个程序1000个或更多个循环之后发生的条件,等待线程发生后

解决方案

您需要条件变量。



如果你的编译器支持C ++ 11引入的 std :: conditional ,那么你可以看到这个细节:





如果您的编译器不支持它,并且使用win32线程,请参阅:





并且这里是一个完整的示例。



如果您使用POSIX线程,请参阅:











  • 您可以在这里查看我使用win32原语的 conditional_variable a href =http://codereview.stackexchange.com/questions/12052/implementation-of-concurrent-blocking-queue-for-producer-consumer>生产者 - 消费者的并发阻止队列的实现



向下滚动并首先查看它的实现,然后查看并发队列实现中的用法。



条件变量的典型用法是:

  //首先锁定互斥体! 
scoped_lock myLock(myMutex);

//等到条件满足
myConditionalVariable.wait(myLock,CheckCondition);

//仅当条件满足时才执行此代码

code> CheckCondition 是一个检查条件的函数(或函子)。当 被唤醒时, wait()函数在内部调用,如果条件还没有满足, wait()函数再次休眠。在进入睡眠之前, wait()会释放互斥体,原子性地。


I want to wait one thread of 2 thread that executed in a Simultaneous simulator until a condition has been occurred, may be the condition occurred after 1000 or more cycles of running a program in the simulator, after the condition occurred the waited thread executed again, how can I do it?

解决方案

You need conditional variables.

If your compiler supports std::conditional introduced by C++11, then you can see this for detail:

If your compiler doesn't support it, and you work with win32 threads, then see this:

And here is a complete example.

And if you work with POSIX threads, then see this:


You can see my implementation of conditional_variable using win32 primitives here:

Scroll down and see it's implementation first, then see the usage in the concurrent queue implementation.

A typical usage of conditional variable is this:

//lock the mutex first!
scoped_lock myLock(myMutex); 

//wait till a condition is met
myConditionalVariable.wait(myLock, CheckCondition);

//Execute this code only if the condition is met

whereCheckCondition is a function (or functor) which checks the condition. It is called by wait() function internally when it spuriously wakes up and if the condition has not met yet, the wait() function sleeps again. Before going to sleep, wait() releases the mutex, atomically.

这篇关于等待线程,直到发生条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆