关于多线程交替打印的问题
题目要求是写3个线程交替递增打印一个整数,直到最大数的限制。我们可以根据取模运算来判断当前该打印那个数字。
但是本人在第一遍写的时候遇到如下三个问题:
- 加锁用的是独占锁,但是忘了用全局互斥量来初始化该锁,也就是写成了
unique_lock<mutex> locker
,应该是unique_lock<mutex> locker(mux)
;
- 在子线程函数里面忘了用while循环,只是循环等待获取锁和判断取模结果是否符合条件,导致打印了一遍后线程就结束运行了;
- 获取锁后还应该判断当前值是否超过限制,不然可能由于在其他线程里面当前值已经由于自增而超限制了;
改正后代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <condition_variable> #include <iostream> #include <mutex> #include <thread>
using namespace std;
int cur = 0; const int limit = 100; condition_variable cv; mutex mux;
void print0() { unique_lock<mutex> locker(mux); while (cur <= limit) { while (cur % 3 != 0) { cv.wait(locker); if (cur > limit) { cv.notify_all(); return; } } cout << "thread0 : cur = " << cur << endl; ++cur; cv.notify_all(); } }
void print1() { unique_lock<mutex> locker(mux); while (cur <= limit) { while (cur % 3 != 1) { cv.wait(locker); if (cur > limit) { cv.notify_all(); return; } } cout << "thread1 : cur = " << cur << endl; ++cur; cv.notify_all(); } }
void print2() { unique_lock<mutex> locker(mux); while (cur <= limit) { while (cur % 3 != 2) { cv.wait(locker); if (cur > limit) { cv.notify_all(); return; } } cout << "thread2 : cur = " << cur << endl; ++cur; cv.notify_all(); } }
int main() { thread t0(print0), t1(print1), t2(print2); t0.join(); t1.join(); t2.join(); cout << "main thread" << endl; system("pause"); return 0; }
|