早期的C++语言并不支持多线程,认为会影响到语言的性能。早期的C++程序多线程的实现是交给操作系统内生API来实现。在C++11之后把Thread类纳入了C++体系,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
| #include <thread> #include <mutex> #include <iostream> using namespace std;
mutex g_mutex; void T1() { g_mutex.lock(); cout << "T1 Hello" << endl; g_mutex.unlock(); } void T2(const char* str) { g_mutex.lock(); cout << "T2 " << str << endl; g_mutex.unlock(); } int main() { thread t1(T1); thread t2(T2, "Hello World"); t1.join(); t2.detach(); cout << "Main Hi" << endl;
return 0; }
|
- thread::join:主线程等待子线程执行结束
- thread::detach:
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 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <iostream> #include <thread> #include <mutex> using namespace std;
void Deposit(mutex& m, int& money) { for(int index = 0; index < 100; index++) { m.lock(); money += 1; m.unlock(); } }
void Withdraw(mutex& m, int& money) { for (int index = 0; index < 100; index++) { m.lock(); money -= 2; m.unlock(); } }
int main() { int money = 2000; mutex m; cout << "Current money is: " << money << endl; thread t1(Deposit, ref(m), ref(money)); thread t2(Withdraw, ref(m), ref(money)); t1.join(); t2.join(); cout << "Finally money is: " << money << endl;
thread tW1([]() { cout << "ThreadSwap1 " << endl; }); thread tW2([]() { cout << "ThreadSwap2 " << endl; }); cout << "ThreadSwap1' id is " << tW1.get_id() << endl; cout << "ThreadSwap2' id is " << tW2.get_id() << endl;
cout << "Swap after:" << endl; swap(tW1, tW2); cout << "ThreadSwap1' id is " << tW1.get_id() << endl; cout << "ThreadSwap2' id is " << tW2.get_id() << endl; tW1.join(); tW2.join();
thread tM1( []() { ; } ); cout << "ThreadMove1' id is " << tM1.get_id() << endl; cout << "Move after:" << endl; thread tM2 = move(tM1); cout << "ThreadMove2' id is " << tM2.get_id() << endl; cout << "ThreadMove1' id is " << tM1.get_id() << endl; tM2.join();
return 0; }
|