首页 > 代码库 > 线程 condition_variable

线程 condition_variable

http://www.cnblogs.com/haippy/p/3252041.html

理解wait();当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex)。在线程被阻塞时,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait()函数也是自动调用 lck.lock(),使得lck的状态和 wait 函数被调用时相同

void wait (unique_lock& lck, Predicate pred);

在第二种情况下(即设置了 Predicate),只有当 pred 条件为false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。

因此第二种情况类似以下代码:

while (!pred()) wait(lck);
#include <iostream>                // std::cout#include <thread>                // std::thread, std::this_thread::yield#include <mutex>                // std::mutex, std::unique_lock  #include <condition_variable>    // std::condition_variable
#include <chrono>             // std::chrono::seconds


std::mutex mtx; std::condition_variable cv;
std::unique_lock <std::mutex> lck(mtx);
while (cv.wait_for(lck,std::chrono::seconds(1)) == std::cv_status::timeout) {
std::cout
<< .; std::cout.flush();
}
bool shipment_available()
{
  return cargo != 0;
}
cv.wait(lck, shipment_available);
cv.wait(lck);
 cv.notify_all();
 cv.notify_one();


http://www.tuicool.com/articles/222yY3

题目:子线程循环  10  次,接着主线程循环  100  次,接着又回到子线程循环  10 次,接着再回到主线程又循环  100  次,如此循环 50 次,试写出代码。注意:一定是子线程先执行,主线程再执行。

 

#include<iostream>  #include<thread>  #include<mutex>  #include<condition_variable>  using namespace std;mutex m;condition_variable cond;int flag = 10;void fun(int num){    for (int i = 0; i<50; i++){        unique_lock<mutex> lk(m);//A unique lock is an object that manages a mutex object with unique ownership in both states: locked and unlocked.          while (flag != num)            cond.wait(lk);//在调用wait时会执行lk.unlock()          for (int j = 0; j<num; j++)            cout << j << " ";        cout << endl;        flag = (num == 10) ? 100 : 10;        cond.notify_one();//被阻塞的线程唤醒后lk.lock()恢复在调用wait前的状态      }}int main(){    thread child(fun, 10);    fun(100);    child.join();    return 0;}

 

线程 condition_variable