admin管理员组文章数量:1599426
c++多线程之condition_variable
- 简介
- 等待线程
- wait()
- wait_for
- wait_until
- 通知线程
- 总结
简介
condition_variable的作用是阻塞线程,然后等待通知将其唤醒。我们可以通过某个函数判断是否符合某种条件来决定是阻塞线程等待通知还是唤醒线程,由此实现线程间的同步。所以简单来说condition_variable的作用就两个——等待(wait)、通知(notify)。下面详细介绍一下。
等待线程
condition_variable的等待函数有三个,分别是wait()——等待、wait_for()——等待一段时间、wait_until()——等待至某一时刻。另外针对每个函数condition_variable还提供了有条件等待和无条件等待两种方式。下面具体讲解一下。
wait()
wait()的是普通的等待。分为有条件的等待和无条件的等待。
函数声明 | 说明 |
---|---|
void wait (unique_lock& lck) | 无条件的等待 |
void wait (unique_lock& lck, Predicate pred) | 有条件的等待 |
- void wait (unique_lock& lck)会无条件的阻塞当前线程然后等待通知,前提是此时对象lck已经成功获取了锁。等待时会调用lck.unlock()释放锁,使其它线程可以获取锁。一旦得到通知(由其他线程显式地通知),函数就会释放阻塞并调用lck.lock(),使lck保持与调用函数时相同的状态。然后函数返回,注意,最后一次lck.lock()的调用可能会在返回前再次阻塞线程。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <windows.h>
std::condition_variable cv;
int value;
void read_value() {
std::cin >> value;
cv.notify_one();
}
int main()
{
std::cout << "Please, enter an integer (I'll be printing dots): \n";
std::thread th(read_value);
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck);
std::cout << "You entered: " << value << '\n';
th.join();
return 0;
}
输出:
Please, enter an integer (I'll be printing dots):
7
You entered: 7
wati()函数因为没有条件判断,因此有时候会产生虚假唤醒,而有条件的等待可以很好的解决这一问题。
- void wait (unique_lock& lck, Predicate pred)为有条件的等待,pred是一个可调用的对象或函数,它不接受任何参数,并返回一个可以作为bool计算的值。当pred为false时wait()函数才会使线程等待,在收到其他线程通知时只有当pred返回true时才会被唤醒。我们将上述代码做如下修改,它的输出与上述一样。
bool istrue()
{
return value != 0;
}
int main()
{
std::cout << "Please, enter an integer (I'll be printing dots): \n";
std::thread th(read_value);
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck,istrue);
std::cout << "You entered: " << value << '\n';
th.join();
return 0;
}
借助条件判断我们还可以做更加复杂的操作。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int cargo = 0;
bool shipment_available() {return cargo!=0;}
void consume (int n) {
for (int i=0; i<n; ++i) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck,shipment_available);
// consume:
std::cout << cargo << '\n';
cargo=0;
}
}
int main ()
{
std::thread consumer_thread (consume,10);
// produce 10 items when needed:
for (int i=0; i<10; ++i) {
while (shipment_available()) std::this_thread::yield();
std::unique_lock<std::mutex> lck(mtx);
cargo = i+1;
cv.notify_one();
}
consumer_thread.join();
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
wait_for
wait_for与wait的不同在于wait_for在没有通知的情况下不会一值阻塞线程,而是等待一段时间后自动唤醒,因此wait_for需要传入一个时间量。与wait相同该函数也分为有条件与无条件两种方式。
当前线程(lck应该已经锁定了互斥锁)的执行在rel_time期间内被阻塞,在阻塞线程时,函数自动调用lck.unlock(),允许其他被锁定的线程继续运行。一旦被通知或rel_time超时,该函数就会释放阻塞并调用lck.lock(),使lck处于与调用该函数时相同的状态。然后函数返回(注意,最后一次lck.lock()可能会在返回前再次阻塞线程)。
函数声明 | 说明 |
---|---|
cv_status wait_for (unique_lock& lck,const chrono::duration<Rep,Period>& rel_time) | 无条件的等待 |
bool wait_for (unique_lock& lck,const chrono::duration<Rep,Period>& rel_time, Predicate pred) | 有条件的等待 |
- cv_status wait_for (unique_lock& lck,const chrono::duration<Rep,Period>& rel_time)的返回值cv_status是一个带作用域枚举,描述定时等待是否因时限返回。当前线程(lck应该已经锁定了互斥锁)的执行在rel_time期间内无条件的被阻塞,在阻塞线程时,函数自动调用lck.unlock(),允许其他被锁定的线程继续运行。一旦被通知或rel_time超时,该函数就会释放阻塞并调用lck.lock(),使lck处于与调用该函数时相同的状态。然后函数返回,注意,最后一次lck.lock()可能会在返回前再次阻塞线程。我们使用wait_for实现上述代码。
void read_value() {
std::cin >> value;
cv.notify_one();
}
int main()
{
std::cout << "Please, enter an integer (I'll be printing dots): \n";
std::thread th(read_value);
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
while (cv.wait_for(lck, std::chrono::seconds(1)) == std::cv_status::timeout) {
std::cout << '.' << std::endl;
}
std::cout << "You entered: " << value << '\n';
th.join();
return 0;
}
输出:
Please, enter an integer (I'll be printing dots):
.
.
.
5
You entered: 5
但有时会出现虚假唤醒
Please, enter an integer (I'll be printing dots):
.
.
You entered: 0
同样为了解决这一问题,我们引入唤醒条件。
- bool wait_for (unique_lock& lck,const chrono::duration<Rep,Period>& rel_time, Predicate pred)的返回值是bool类型。与无条件不同的是,当前线程(lck应该已经锁定了互斥锁)的执行在rel_time期间内只有当pred为false时才会被阻塞,并且通知只能在线程为true时解除阻塞。如果因超时被唤醒。函数只能返回pred的值,注意,最后一次lck.lock()可能会在返回前再次阻塞线程。为此我们可以很好解决虚假唤醒的问题。
int main()
{
std::cout << "Please, enter an integer (I'll be printing dots): \n";
std::thread th(read_value);
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
while (!cv.wait_for(lck, std::chrono::seconds(1),istrue)) {
std::cout << '.' << std::endl;
}
std::cout << "You entered: " << value << '\n';
th.join();
return 0;
}
wait_until
wait_until与wait_for的使用方式一样,唯一不同的在于第二参数,wait_until设置的是时间点。由于时间点的设置复杂,在这里就不再详细举例。
通知线程
condition_variable的通知函数有两个,notify_one和notify_all,两个函数的区别在于,notify_one通知解除一个线程的阻塞状态,而notify_all通知解除所有线程的阻塞状态,如果当前只有一个等待线程,两者的效果相同,通知该线程解除阻塞;如果没有线程等待,则两者什么都不做;如果有多个线程,notify_one随机选择线程唤醒,而notify_all唤醒所有线程但线程之间争夺锁。
- notify_one例子:
#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 produce,consume;
int cargo = 0; // shared value by producers and consumers
void consumer () {
std::unique_lock<std::mutex> lck(mtx);
while (cargo==0) consume.wait(lck);
std::cout << cargo << '\n';
cargo=0;
produce.notify_one();
}
void producer (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (cargo!=0) produce.wait(lck);
cargo = id;
consume.notify_one();
}
int main ()
{
std::thread consumers[10],producers[10];
// spawn 10 consumers and 10 producers:
for (int i=0; i<10; ++i) {
consumers[i] = std::thread(consumer);
producers[i] = std::thread(producer,i+1);
}
// join them back:
for (int i=0; i<10; ++i) {
producers[i].join();
consumers[i].join();
}
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
- notify_all例子:
#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;
}
输出:
10 threads ready to race...
thread 6
thread 2
thread 5
thread 3
thread 4
thread 1
thread 7
thread 0
thread 9
thread 8
总结
condition_variable的等待函数按需选择,如果在条件不满足的情况下无任务可做,可选择wait将线程阻塞;如果在条件不满足的情况下需要做其他任务,那就不能阻塞而是去做其他任务,然后定期检查条件是否满足,这种情况下可以选择wait_for或wait_until。但无论选择哪个等待函数,都建议大家选择有条件等待,这样才不会出现虚假唤醒的情形。
本文标签: 多线程conditionvariable
版权声明:本文标题:c++多线程之condition_variable 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728322013a1153947.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论