#include <iostream>
#include<thread>
using namespace std;
void changeNum(int& x){
for(int i = 0;i < 1000000000; i ++){
x ++;
}
}
int main() {
int x = 0;
thread t(changeNum, ref(x));
t.detach();//使用detach表示该线程分离于主线程一部执行,主线程结束后std::thread对象不再有对t的控制权
//如果用t.join(),则会使子线程执行之后才会向下执行主线程的代码。
for(int i = 0;i < 20; i ++)
cout << x << endl;
return 0;
}
执行结果:
0
60358
275594
941626
1101499
1244993
1385245
1524483
1746679
1928264
2144337
2285634
2399748
2514134
2633912
2746722
2860747
2974722
3092752
3208152
这说明子线程和主线程是异步执行的,子线程不会阻塞主线程
如果使用join(),则会输出1000000000