C++ 等待线程直到条件发生

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10974829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:41:35  来源:igfitidea点击:

waiting thread until a condition has been occurred

c++multithreadingsimulator

提问by Angelia Wikin

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?

我想等待在 Simultaneous 模拟器中执行的 2 个线程中的一个线程,直到条件发生,可能是在模拟器中运行程序 1000 个或更多周期后发生条件,条件发生后等待的线程再次执行,我该怎么做?

回答by Nawaz

You need conditional variables.

您需要条件变量。

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

如果您的编译器支持std::conditionalC++11 引入的,那么您可以查看此详细信息:

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

如果您的编译器不支持它,并且您使用的是 win32 线程,请查看以下内容:

And hereis a complete example.

这里是一个完整的例子。

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

如果您使用 POSIX 线程,请查看以下内容:



You can see my implementation of conditional_variableusing win32 primitives here:

你可以conditional_variable在这里看到我使用 win32 原语的实现:

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

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

whereCheckCondition是检查条件的函数(或函子)。它wait()虚假唤醒时由函数内部调用,如果条件尚未满足,wait()函数将再次休眠。在睡觉之前wait()原子地释放互斥锁。

回答by jxh

If you don't have C++11, but you do have a system that supports POSIX threads, then you can use a condition variable. There are other choices, but a condition variable may be the most straight forward given the way you have described your problem.

如果您没有 C++11,但您有一个支持 POSIX 线程的系统,那么您可以使用条件变量。还有其他选择,但鉴于您描述问题的方式,条件变量可能是最直接的。

A pthread condition variable is used in conjunction with a mutex. The trick with the condition variable is that waiting on it causes the acquired mutex to be released, until the wait call returns, at which point the mutex has been acquired again. The sequence is:

pthread 条件变量与互斥锁结合使用。条件变量的诀窍在于等待它会导致释放获取的互斥量,直到等待调用返回,此时互斥量已再次获取。顺序是:

  • acquire mutex
  • while PREDICATE is not true
    • wait on condition variable
  • do work on critical section
  • if PREDICATE is true
    • signal condition variable
  • release mutex
  • 获取互斥量
  • 而 PREDICATE 不是真的
    • 等待条件变量
  • 做关键部分的工作
  • 如果 PREDICATE 为真
    • 信号条件变量
  • 释放互斥锁

The signal step is used in case multiple threads are entering the same critical section above.

如果多个线程进入上述相同的临界区,则使用信号步骤。

If a different thread may access the same mutex to modify state that affects the PREDICATE, that thread should check to see if anyone needs to be signaled.

如果不同的线程可以访问相同的互斥锁来修改影响 PREDICATE 的状态,则该线程应检查是否需要向任何人发出信号。

  • acquire mutex
  • do work on critical section
  • if PREDICATE is true
    • signal condition variable
  • release mutex
  • 获取互斥量
  • 做关键部分的工作
  • 如果 PREDICATE 为真
    • 信号条件变量
  • 释放互斥锁

The POSIX commands of interest are:

感兴趣的 POSIX 命令是:

pthread_mutex_init()
pthread_mutex_destroy()
pthread_mutex_lock()
pthread_mutex_unlock()
pthread_cond_init()
pthread_cond_destroy()
pthread_cond_wait()
pthread_cond_signal()

回答by parasrish

Using Semaphore for signalling. Example (application clean exit) as below:

使用信号量发送信号。示例(应用程序干净退出)如下:

Declare in header

在标题中声明

static sem_t semPrepareExit;            //declaration

In source (main thread);

在源(主线程)中;

sem_init(&semPrepareExit, 0, 0);        ///semaphore initialized
...
///now wait for the signal on the semaphore, to proceed hereforth
sem_post(&semPrepareExit);
/// cleanup ahead
...

In source, (spawned-thread);

在源代码中,(生成线程);

...
sem_post(&semPrepareExit);

Now, as soon as you signal on the semaphore using "sem_post". The main-thread will receive the signal at the wait-node/point, and will proceed, there-forth.

现在,只要您使用“sem_post”在信号量上发出信号。主线程将在等待节点/点接收信号,然后继续执行。

回答by serup

try something like this :

尝试这样的事情:

class CmyClass
{
   boost::mutex mtxEventWait;
   bool WaitForEvent(long milliseconds);
   boost::condition cndSignalEvent;
};

bool CmyClass::WaitForEvent(long milliseconds)
{
   boost::mutex::scoped_lock mtxWaitLock(mtxEventWait);
   boost::posix_time::time_duration wait_duration = boost::posix_time::milliseconds(milliseconds); 
   boost::system_time const timeout=boost::get_system_time()+wait_duration; 
   return cndSignalEvent.timed_wait(mtxEventWait,timeout); // wait until signal Event 
}

// so inorder to wait then call the WaitForEvent method

// 所以为了等待然后调用WaitForEvent方法

WaitForEvent(1000); // it will timeout after 1 second

// this is how an event could be signaled:

// 这是一个事件的信号方式:

cndSignalEvent.notify_one();