std::condition_variable

/*
std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程。
在线程被阻塞时,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait() 函数也是自动调用 lck.lock(),使得 lck 的状态和 wait 函数被调用时相同。
在第二种情况下(即设置了 Predicate),只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞
*/
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <condition_variable>
std::vector<int> vec;
std::mutex mu; 
std::condition_variable cv;
int countt = 0;
bool ready = false;
using namespace  std;
void fun(int n)
{
    std::unique_lock<std::mutex> loc(mu);
    while (!ready)
    {
        cv.wait(loc);//依照上面的理解:wait操作线程被阻塞,wait操作会将mutex解锁,导致其他的线程都阻塞在这,当其他线程调用notify时,线程解除阻塞,但开始上锁
    }
    
    int num = 50;
    while (num--)
    {
        cout<<n<<"--------"<<num<<endl;
    }
}

void go()
{
    std::unique_lock<std::mutex> lo(mu);
    ready = true;
    cv.notify_all();//通知所有阻塞的线程进入运行状态
}

int main()
{
    std::thread th[5];
    for (int i = 0; i < 5; ++i)
    {
        th[i] = std::thread(fun, i);
    }
    //此时5个线程都开始运行,但都被阻塞住了
    go();
    for (auto& t:th)
    {
        t.join();
    }
    system("pause");
    return 0;
}

具体参考http://www.cnblogs.com/haippy/p/3252041.html

cv.wait(loc)会解锁,此时阻塞在go函数的线程和fun里面的线程也可以运行,我实在没想通,感觉这个例子举得不好。
原文地址:https://www.cnblogs.com/zzyoucan/p/3673073.html