C++ Thread操作
// thread Operation // #include "stdafx.h" #include<iostream> #include<thread> #include <Windows.h> #include<mutex> using namespace std; #define takeNum(n) printf("num_"#n"=%d",num_##n); int count12 = 24; int num_12 = 24; mutex m; //定义mutex void t1(); void t2(); int _tmain(int argc, _TCHAR* argv[]) { //cout << 1 << endl; thread th1(t1); thread th2(t2); cout << th1.joinable() << endl; th1.join();//该线程停止主线程才会退出 th2.detach();//detach线程对象与线程分离,线程对象不能对线程做控制,线程对象释放不会影响线程的继续执行,但主线程推出线程会停止 cout << th1.joinable() << endl; takeNum(12); char c; cin >> c; return 0; } void t1(){ for (int i = 0; i < 20; i++){ //m.lock(); //上锁 lock_guard<mutex> lockGuard(m); //可以防止程序异常退出,不能unlock,可以自动释放锁 //cout << i << "!" << endl; //m.unlock(); //释放锁 } } void t2(){ for (int i = 0; i < 10; i++){ //m.lock(); //上锁 lock_guard<mutex> lockGuard(m); //cout << i << "@" << endl; //m.unlock(); //释放锁 } }
01-06
7771
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-21
3635
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)