这篇文章是有关线程与并发的最后一篇文章,随后会综合之前讲的,完成一个小例子:如何用几十行代码实现一个线程池。
std::condition_variable是条件变。Linux下使用 Pthread库中的 pthread_cond_*() 函数提供了与条件变量相关的功能。和pthread_cond_*()一样,我们可以使用条件变量(condition_variable)实现多个线程间的同步操作;当条件不满足时,相关线程被一直阻塞,直到某种条件出现,这些线程才会被唤醒。C++11通过std::condition_variable,对于条件变量进行了统一化,标准化。
condition_variable 的用法很简单,这里就不一一介绍了。关键用法如下图所示:
我们来看看官方的解释:
condition_variable 类是同步原语,能用于阻塞一个线程,或同时阻塞多个线程,直至另一线程修改共享变量(条件)并通知 condition_variable 。
有意修改变量的线程必须:
-
获得 std::mutex (常通过 std::lock_guard )
-
在保有锁时进行修改
-
在 std::condition_variable 上执行 notify_one 或 notify_all (不需要为通知保有锁)
即使共享变量是原子的,也必须在互斥下修改它,以正确地发布修改到等待的线程。
任何有意在 std::condition_variable 上等待的线程必须:
-
在与用于保护共享变量者相同的互斥上获得 std::unique_lock<std::mutex>
-
执行下列之一:
-
-
使用 wait 、 wait_for 及 wait_until 的有谓词重载,它们包揽以上三个步骤
-
检查条件,是否为已更新或提醒它的情况
-
执行 wait 、 wait_for 或 wait_until ,等待操作自动释放互斥,并悬挂线程的执行。
-
condition_variable 被通知时,时限消失或虚假唤醒发生,线程被唤醒,且自动重新获得互斥。之后线程应检查条件,若唤醒是虚假的,则继续等待。
-
std::condition_variable 只可与 std::unique_lock<std::mutex> 一同使用;此限制在一些平台上允许最大效率。std::condition_variable_any 提供可与任何基本可锁定 (BasicLockable) 对象,例如 std::shared_lock 一同使用的条件变量。
condition_variable容许:
wait 、 wait_for 、 wait_until 、 notify_one 及 notify_all 成员函数的同时调用。
类 std::condition_variable 是标准布局类型 (StandardLayoutType) 。它非可复制构造 (CopyConstructible) 、可移动构造 (MoveConstructible) 、可复制赋值 (CopyAssignable) 或可移动赋值 (MoveAssignable) 。
下面看一下官网的例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto& th : threads) th.join();
return 0;
}
Output:
10 threads ready to race...
thread 2
thread 0
thread 9
thread 4
thread 6
thread 8
thread 7
thread 5
thread 3
thread 1
关注公众号获取更多信息: