C++多线程笔记(持续更新)

引入头文件thread

#include<thread>

写一个测试函数

void func1() {
	cout << "my thread1, thread id is "
		<< this_thread::get_id()<<endl;//获取子线程1的id
}

在主函数内定义一个线程,调用func1
int main(){
thread myThead1(func1);//调用函数
	myThead1.join();//阻塞主线程(子线程运行完,才运行主线程)。
cout << "This is main thread, thread id is "
		<< this_thread::get_id()<< endl;
}

运行结果如下:

alt

如果使用detach()函数,则不阻塞主线程,可能会出现下面的结果

alt

这是由于cout不是线程安全的。

joinable()用于返回是否可以join()或者detach();

int main(){
thread myThead1(func1);//调用函数
	myThead1.detach();
	if (myThead1.joinable() == true) {
		cout << true << endl;
	}
	else {
		cout << false << endl;
	}
  return 0;
}

输出结果如下

alt

这是由于线程已经join()或者detach()过了,所以不能再join()或者detach()

全部评论

相关推荐

每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:10
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务