我正在读书pthread.h; 条件变量相关函数(如pthread_cond_wait(3))需要互斥量作为参数.为什么?据我所知,我将创建一个互斥体只是用作该参数?那个互斥锁应该做什么?
我对使用有点困惑std::condition_variable.我明白我必须创建unique_lock一个mutex调用之前condition_variable.wait().我无法找到是我是否也应该调用之前获得一个独特的锁notify_one()或notify_all().
cppreference.com上的示例存在冲突.例如,notify_one页面提供了以下示例:
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cout << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cout << "...finished waiting. i == 1\n";
done = true;
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Notifying...\n";
cv.notify_one();
std::unique_lock<std::mutex> lk(cv_m);
i = 1;
while (!done) {
lk.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1)); …Run Code Online (Sandbox Code Playgroud) 在用C++ 11编写的分布式作业系统中,我使用以下结构实现了一个fence(即工作线程池外部的线程可能会要求阻塞,直到完成所有当前计划的作业):
struct fence
{
std::atomic<size_t> counter;
std::mutex resume_mutex;
std::condition_variable resume;
fence(size_t num_threads)
: counter(num_threads)
{}
};
Run Code Online (Sandbox Code Playgroud)
实现fence的代码如下所示:
void task_pool::fence_impl(void *arg)
{
auto f = (fence *)arg;
if (--f->counter == 0) // (1)
// we have zeroed this fence's counter, wake up everyone that waits
f->resume.notify_all(); // (2)
else
{
unique_lock<mutex> lock(f->resume_mutex);
f->resume.wait(lock); // (3)
}
}
Run Code Online (Sandbox Code Playgroud)
如果线程在一段时间内进入围栏,这种方法非常有效.然而,如果他们几乎同时尝试这样做,似乎有时会发生在原子递减(1)和开始条件var(3)的等待之间,线程产生CPU时间而另一个线程将计数器递减到零( 1)并解雇cond.var(2).这导致前一个线程在(3)中永远等待,因为它已经被通知后开始等待它.
让事情变得可行的黑客就是在(2)之前进行10毫秒的睡眠,但这显然是不可接受的.
有关如何以高效的方式解决这个问题的任何建议?
我正在运行以下代码块。此代码将创建 5 个从属线程和 1 个主线程。所有从线程等待主线程准备好数据,当数据准备好时,所有从线程将通知开始处理。
我的问题是,有可能在从线程开始等待之前conditional_variable,主线程准备好数据并通知等待的线程。在这种情况下,一些等待的线程将获得通知并开始处理,但未等待的线程将开始等待永远不会到来的通知。
如果您运行此示例,则不会发生这种情况,但我正在寻找一种方法来确保所有从属线程都在等待通知,然后通知它们。你知道我该怎么做吗?
/*
Condition Variables - Many waiting threads
Shows how one condition variable can be used to notify multiple threads
that a condition has occured.
* Part of "Threading with Boost - Part IV: Condition Variables", published at:
http://antonym.org/boost
Copyright (c) 2015 Gavin Baker <gavinb@antonym.org>
Published under the MIT license, see LICENSE for details
*/
#include <cstdio>
#include <boost/thread.hpp>
boost::condition_variable data_ready_cond;
boost::mutex data_ready_mutex;
bool data_ready = false;
void master_thread()
{
printf("+++ master …Run Code Online (Sandbox Code Playgroud)