函数介绍
lock_guard:锁定互斥锁后,生命周期结束后会自动释放,不需要手动解锁,也无法手动解锁
unique_lock:多数情况与上面一个可以相互替代,但是其更具功能性(付出一些代价)。unique_lock可以进行unlock操作,因此可以和条件变量搭配使用
多线程输出数字
多个线程互斥输出: 0 1 2 3 4 5 6 ...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <iostream> #include <vector> #include <thread> #include <mutex> using namespace std; int idx = 0; mutex _mutex; void func(int n) { while (idx < n) { lock_guard<mutex> tmp(_mutex); if (idx >= n) break; cout << idx++ << " "; } } int main() { vector<thread> arr; for (int i = 0; i < 10; ++i) arr.push_back(thread(func, 1000)); for (auto& e : arr) e.join(); return 0; }
|
版本2
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
| #include <iostream> #include <vector> #include <thread> #include <mutex> #include <windows.h> using namespace std; int idx = 0; mutex _mutex; void func(int n) { while (idx < n) { lock_guard<mutex> tmp(_mutex); if (idx >= n) break; cout << idx++ << " "; } } int main() { vector<thread> arr; for (int i = 0; i < 10; ++i) { auto t = thread(func, 1000); t.detach(); arr.push_back(move(t)); } Sleep(1000); return 0; }
|
多线程输出ABC
多个线程互斥输出:
1 2 3 4 5
| A B C A B C A B C A B C ...
|
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
| #include <iostream> #include <thread> #include <mutex> using namespace std;
mutex _mutex; int step = 0; int stepNum = 0; void func1() { while (true) { lock_guard<mutex> tmp(_mutex); if (stepNum == 30) break; if (step % 3 == 0) { ++step; ++stepNum; cout << "A" << " "; } } }
void func2() { while (true) { lock_guard<mutex> tmp(_mutex); if (stepNum == 30) break; if (step % 3 == 1) { ++step; ++stepNum; cout << "B" << " "; } } }
void func3() { while (true) { lock_guard<mutex> tmp(_mutex); if (stepNum == 30) break; if (step % 3 == 2) { ++step; ++stepNum; cout << "C" << endl; } } }
int main() { thread t1(func1); thread t2(func2); thread t3(func3); t1.join(); t2.join(); t3.join(); return 0; }
|
条件变量
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
| #include <iostream> #include <thread> #include <mutex> #include <windows.h> #include <condition_variable> using namespace std; mutex _mutex; condition_variable cv; bool ready = false;
void workers(int id) { unique_lock<mutex> ulck(_mutex); while (ready == false) { cout << "here: "<< id << endl; cv.wait(ulck); } cout << "thread: " << id << endl; } void go() { unique_lock<mutex> ulck(_mutex); ready = true; cv.notify_all(); } int main() { thread mt[10]; for (int i = 0; i < 10; ++i) mt[i] = thread(workers, i); cout << "10 threads ready to race...(already!)" << endl; Sleep(50); go(); for (auto& e : mt) e.join(); return 0; }
|