c++多线程之condition_variable

简介

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。但无论选择哪个等待函数,都建议大家选择有条件等待,这样才不会出现虚假唤醒的情形。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值