C++ 0x 使用condition_variable 与 Mutex 同步两个线程

Mutex : 锁   同一时间只允许一个线程访问其代码内容

拟人 : 就是一把锁而已,可以lock unlock, 谁都可以拿到锁,打开门进屋,但进去后,就会把门锁上(lock) 别人想进就得等他出来(unlock).

Condition_variable : 条件变量    用来阻塞线程, 在收到信号 或 满足某条件 或 等待超过某设定的时间 时继续运行线程

拟人 : 相当于 拿着锁 (用锁来初始化) 的保安同志.. 他拿着锁,有权力控制门的打开与关闭,他是按着上级的 指示/时间/条件 才会打开大门的

 1 #include <iostream>
 2 #include <condition_variable>
 3 #include <thread>
 4 using namespace std;
 5 
 6 // 条件变量
 7 condition_variable cv;
 8 //
 9 mutex m;
10 // 这个值 是0 还是1 决定了哪个线程运行 哪个线程阻塞
11 int currentAppend = 0;
12 
13 // 线程1
14 void append_1() {
15     // 线程1的锁
16     unique_lock<mutex> lock(m);
17     for (size_t i = 0; i < 5; i++)
18     {
19         /*
20             用锁来初始化条件变量并阻塞,后面跟的是一个谓语表达示
21             也就是说,在满足什么条件的时候(返回True),线程才能继续运行
22             这里就是在 currentAppend 为 1 的时候继续
23         */
24         cv.wait(lock, []{return currentAppend == 1; });
25         cout << "append " << 1 << endl;
26         // 在这里改变了条件(也就是将值改为了0)
27         currentAppend = 0;
28         // 这是条件变量在做完一些操作的时候,告诉其它的正在阻塞的线程
29         // 你们可以继续了
30         cv.notify_one();
31     }
32 }
33 
34 // 线程2
35 void append_0() {
36     // 线程2的锁
37     unique_lock<mutex> lock(m);
38     for (size_t i = 0; i < 5; i++)
39     {
40         // 同上方解释
41         cv.wait(lock, []{return currentAppend == 0; });
42         cout << "append " << 0 << endl;
43         currentAppend = 1;
44         cv.notify_one();
45     }
46 }
47 
48 int main() {
49     // 创建两个线程
50     thread th_0(append_0);
51     thread th_1(append_1);
52 
53     // 等待两个线程运行完成
54     th_0.join();
55     th_1.join();
56 
57     return 0;
58 }

 

posted @ 2013-12-04 23:53  easyfrog  阅读(673)  评论(0编辑  收藏  举报