C++知识点-线程2-线程管理
程序员文章站
2022-05-05 18:37:56
...
线程管理就是使用join或detach来管理线程。
第一个版本,注意在异常中增加对线程的join
#include <iostream>
#include <thread>
using namespace std;
void function_1(){
std::cout<<"beauty is only skin-deep"<<std::endl;
}
int main(){
std::thread t1(function_1); //t1 starts ruing
try{
}catch(...){
t1.join();
throw;
}
t1.join();
return 0;
}
第二个版本,包一层
#include <iostream>
#include <thread>
using namespace std;
class Fctor{
public:
void operator()(){
for(int i = 0; i >-100; i--){
cout<<"from t1 "<<i<<endl;
}
}
};
int main(){
std::thread t1((Fctor())); //t1 starts ruing
try{
}catch(...){
t1.join();
throw;
}
t1.join();
return 0;
}
第三个版本,包装层传参
#include <iostream>
#include <thread>
using namespace std;
class Fctor{
public:
void operator()(string &msg){
cout<<"t1 says "<<msg<<endl;
msg = "Trust is the mother of deceit."
}
};
int main(){
string s = "where there is no trust, there is no love";
std::thread t1((Fctor()), s); //t1 starts ruing
try{
}catch(...){
t1.join();
throw;
}
t1.join();
cout<<"from main: "<<s<<endl;
return 0;
}
这个版本引用没有起作用,如果想用引用起作用,需要写成下边这样
#include <iostream>
#include <thread>
using namespace std;
class Fctor {
public:
void operator()(string &msg) {
std::cout << "t1 says "<<msg.c_str() << endl;
msg = "Trust is the mother of deceit.";
}
};
int main() {
string s = "where there is no trust, there is no love";
std::thread t1((Fctor()), std::ref(s)); //t1 starts ruing
try {
}
catch (...) {
t1.join();
throw;
}
t1.join();
cout << "from main: " << s.c_str() <<endl;
return 0;
}
底层内存移动的话,可以写成这样
#include <iostream>
#include <thread>
using namespace std;
class Fctor {
public:
void operator()(string &msg) {
std::cout << "t1 says "<<msg.c_str() << endl;
msg = "Trust is the mother of deceit.";
}
};
int main() {
string s = "where there is no trust, there is no love";
std::thread t1((Fctor()), std::move(s)); //t1 starts ruing
try {
}
catch (...) {
t1.join();
throw;
}
t1.join();
cout << "from main: " << s.c_str() <<endl;
return 0;
}
最后的话:
我是一个工作10年的程序员,工作中经常会遇到需要查一些关键技术,但是很多技术名词的介绍都写的很繁琐,为什么没有一个简单的/5分钟能说清楚的博客呢. 我打算有空就写写这种风格的指南文档.CSDN上搜蓝色的杯子, 没事多留言,指出我写的不对的地方,写的排版风格之类的问题,让我们一起爱智求真吧aaa@qq.com是我的邮箱,也可以给我邮箱留言.