c++的thread小测试

2023-04-28,

windows环境还用不了thread,得下一些mingw,弄了半天没弄好,直接用了商店中心就有的Ubuntu了,但是sudo install g++出现了下载不了的问题,解决方案:https://blog.csdn.net/qq_35451572/article/details/79516563

说几个函数:

thread.join()是阻塞模式,就是这个线程不跑完,下个不动。
thread.detach()与上个相反。
mutex.lock()是个死循环的锁。

单纯的多线程

long long x = 0;
void t(int num){
for(int i = 1; i <= 1000000; i++){
x++;
}
cout << num << ' ' << x << '\n';
} int main(){
for(int i = 1; i <= 10; i++){
thread th(t, i);
th.detach();
}
string t; cin >> t;
cout << "tot " << x << endl;
cin >> t;
return 0;
}

测试结果:

6 946759
2 1049349
4 1056640
9 1100205
1 1166397
3 1231131
5 1294207
7 1356112
8 2101257
10 2113748
asf
tot 2113748
dsf

加锁的多线程

mutex flag;
long long x = 0;
void t(int num){
flag.lock();
for(int i = 1; i <= 1000000; i++){
x++;
}
cout << num << ' ' << x << '\n';
flag.unlock();
} int main(){
for(int i = 1; i <= 10; i++){
thread th(t, i);
th.detach();
}
string t; cin >> t;
cout << "tot " << x << endl;
cin >> t;
return 0;
}

测试结果:

1 1000000
2 2000000
3 3000000
4 4000000
5 5000000
6 6000000
7 7000000
8 8000000
9 9000000
10 10000000
asd
tot 10000000
asd

c++的thread小测试的相关教程结束。

《c++的thread小测试.doc》

下载本文的Word格式文档,以方便收藏与打印。