设为首页 加入收藏

TOP

C++11并发编程-条件变量(condition_variable)详解(一)
2015-11-21 00:58:41 来源: 作者: 【 】 浏览:7
Tags:并发 编程 条件 变量 condition_variable 详解

头文件主要包含了与条件变量相关的类和函数。相关的类包括 std::condition_variablestd::condition_variable_any,还有枚举类型std::cv_status。另外还包括函数 std::notify_all_at_thread_exit(),下面分别介绍一下以上几种类型。

std::condition_variable 类介绍

std::condition_variable是条件变量,更多有关条件变量的定义参考维基百科。Linux下使用 Pthread库中的 pthread_cond_*() 函数提供了与条件变量相关的功能, Windows 则参考 MSDN

std::condition_variable对象的某个wait 函数被调用的时候,它使用 std::unique_lock(通过 std::mutex) 来锁住当前线程。当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable 对象上调用了 notification 函数来唤醒当前线程。

std::condition_variable 对象通常使用 std::unique_lock 来等待,如果需要使用另外的 lockable 类型,可以使用std::condition_variable_any类,本文后面会讲到 std::condition_variable_any 的用法。

#include 
   
     // std::cout #include 
    
      // std::thread #include 
     
       // std::mutex, std::unique_lock #include 
      
        // std::condition_variable std::mutex mtx; // 全局互斥锁. std::condition_variable cv; // 全局条件变量. bool ready = false; // 全局标志位. void do_print_id(int id) { std::unique_lock 
       
         lck(mtx); while (!ready) // 如果标志位不为 true, 则等待... cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后, // 线程被唤醒, 继续往下执行打印线程编号id. std::cout << "thread " << id << '\n'; } void go() { std::unique_lock 
        
          lck(mtx); ready = true; // 设置全局标志位为 true. cv.notify_all(); // 唤醒所有线程. } int main() { std::thread threads[10]; // spawn 10 threads: for (int i = 0; i < 10; ++i) threads[i] = std::thread(do_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 1
thread 0
thread 2
thread 3
thread 4
thread 5
thread 6
thread 7
thread 8
thread 9

好了,对条件变量有了一个基本的了解之后,我们来看看 std::condition_variable 的各个成员函数。

std::condition_variable 的拷贝构造函数被禁用,只提供了默认构造函数。

std::condition_variable::wait() 介绍:

void wait (unique_lock
   
    & lck); template 
    
      void wait (unique_lock
     
      & lck, Predicate pred);
     
    
   

std::condition_variable提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程。

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

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

while (!pred()) wait(lck);
#include 
   
     // std::cout #include 
    
      // std::thread, std::this_thread::yield #include 
     
       // std::mutex, std::unique_lock #include 
      
        // std::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 
       
         lck(mtx); cv.wait(lck, shipment_available); std::cout << cargo << '\n'; cargo = 0; } } int main() { std::thread consumer_thread(consume, 10); // 消费者线程. // 主线程为生产者线程, 生产 10 个物品. for (int i = 0; i < 10; ++i) { while (shipment_available()) std::this_thread::yield(); std::unique_lock 
        
          lck(mtx); cargo = i + 1; cv.notify_one(); } consumer_thread.join(); return 0; }
        
       
      
     
    
   
1
2
3
4
5
6
7
8
9
10

std::condition_variable::wait_for() 介绍

template 
   
     cv_status wait_for (unique_lock
    
     & lck, const chrono::duration
     
      & rel_time); template 
      
        bool wait_for (unique_lock
       
        & lck, const chrono::duration
        
         & rel_time, Predicate pred);
        
       
      
     
    
   

std::condition_variable::wait() 类似,不过 wait_for可以指定一个时间段,在当前线程收到通知或者指定的时间 rel_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_for返回,剩下的处理步骤和 wait()类似。

另外,wait_for 的重载版本的最后一个参数pred表示 wait_for的预测条件,只有当 pred条件为false时调用 wait()才会阻塞当前线程,并且在收到其他线程的通知后只有当 predtrue时才会被解除阻塞,因此相当于如下代码:

return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));

请看下面的例子(参考),下面的例子中,主线程等待th线程输入一个值,然后将th线程从终端接收的值打印出来,在th线程接受到值之前,主线程一直等待,每个一秒超时一次,并打印一个 "."

#include 
   
     // std::cout #include 
    
      // std::thread #include 
     
       // std::chrono::seconds #include 
      
        // std
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode204:Count Primes 下一篇C++入门学习――标准模板库之vect..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: