c++ thread join detach用法

c++ thread join用法

#include <thread>
#include <mutex>
#include <iostream>

using namespace std;

void downlaod1()
{
	cout<<"d1"<<endl;

	for (int i = 0; i < 100; ++i)
	{
		/* code */
		std::this_thread::sleep_for(chrono::milliseconds(50));
		cout <<"下载进度1...."<< i<<endl;
	}
	cout <<"d1 successful!"<<endl;
}

void downlaod2()
{
	cout<<"d2"<<endl;

	for (int i = 0; i < 100; ++i)
	{
		/* code */
		std::this_thread::sleep_for(chrono::milliseconds(80));
		cout<<"下载进度2...."<< i<<endl;
	}
	cout <<"下载完成2"<<endl;
}


void process()
{
	cout <<"start process d1 and d2!\n"<<endl;
}

int main(int argc, char const *argv[])
{
	/* code */
	cout<<"main run!\n";

	thread d2(downlaod2);
	downlaod1();
	d2.join();

	process();

	return 0;
}
  1. g++ _thread_join.cpp -o test -lpthread
  2. -lpthread必须加上,不加会报thread_creat不存在的错误
  3. 在这里插入图片描述
    从上面的结果看到,d2.join()的加入会使线程download1做完事情后,等待线程download2结束,共同执行process(),所以join()是必须等到线程执行完毕后返回

detach

#include <thread>
#include <iostream>
#include <mutex>

using namespace std;

void download1()
{
	for (int i = 0; i < 100; ++i)
	{
		/* code */
		std::this_thread::sleep_for(chrono::milliseconds(5));
		cout<<"d1 进度 ......"<< i<<endl;
	}
	cout<<"d1 sucessful!\n"<<endl;
}

void download2()
{
	for (int i = 0; i < 100; ++i)
	{
		/* code */
		this_thread::sleep_for(chrono::milliseconds(5));
		cout<<"d2 进度........"<<endl;
	}
	cout<<"d2 sucessful!\n"<<endl;
}

void process()
{
	cout<<"d1 ok ,d2 ok"<<endl;
}


int main(int argc, char const *argv[])
{
	/* code */
	cout<<"main run!\n"<<endl;
	
	thread d1(download1);
	thread d2(download2);

	d1.detach();//detach 使主线程与子线程并行执行
	d2.detach();

	for (int i = 0; i < 5; ++i)
	{
		/* code */
		this_thread::sleep_for(chrono::milliseconds(15));
		cout <<"main run process..."<< i<<endl;

	}

	process();


	return 0;
}
  1. 在这里插入图片描述
    对于join来说,detach使主线程和子线程并行,这样就不会应用join时候,带来的主线程阻塞的问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PI_sunyang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值