admin管理员组

文章数量:1599543

简介

条件变量std::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


 

本文标签: 深度十七waitconditionvariable