c++中thread::join()与thread1::detach()区别

thread::join()与thread::detach()方法两者区别在于主线程是否被阻塞。
使用thread::join()释放线程后,由系统分配给该线程的内存全部被清空并释放,所以只能执行一次,但是再执行join之前,主线程不能做其他事情。
使用thread::detach()方法后,将导致与指向该线程的指针分离,即主线程失去了对该线程的控制,主线程并不需要等待该线程结束而结束,该线程会再执行结束之后自行释放空间。
用代码表示如下:
没有加入线程效果

void hellowworld()
{
	int i = 10;
	while (i--)
	{
		cout << " hello world" << endl;
	}	
}

void helloguangzhou()
{
	int i = 10;
	while (i--) {
		cout << " hello guangzhou" << endl;
	}	
}
int main()
{
    hellowworld();
	helloguangzhou();
  return 0;
}

输出是按着顺序输出的。

 hello world
 hello world
 hello world
 hello world
 hello world
 hello world
 hello world
 hello world
 hello world
 hello world
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou

加入线程并使用thread::join()释放效果

void helloguangzhou()
{
    
    
	int i = 10;
	while (i--) {
    
    
		cout << " hello guangzhou" << endl;
	}
	
}
void hellowworld()
{
    
    
	int i = 10;
	while (i--)
	{
    
    
		cout << " hello world" << endl;
	}

}
int main()
{
    
    
std::thread t(hellowworld);
	
	std::thread s(helloguangzhou);
	t.join();
	s.join();
return 0;
}

输出和上面的例子不一样,它不是按顺序的,因为这两个线程在同时进行。

 hello world
 hello world
 hello world
 hello guangzhou
 hello guangzhou
 hello world
 hello world
 hello world
 hello world
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello world
 hello world
 hello world

加入线程并使用thread::detach()释放效果

void helloguangzhou()
{
    
    
	int i = 10;
	while (i--) {
    
    
		cout << " hello guangzhou" << endl;
	}
	
}
void hellowworld()
{
    
    
	int i = 10;
	while (i--)
	{
    
    
		cout << " hello world" << endl;
	}

}
int main()
{
    
    
std::thread t(hellowworld);
	
	std::thread s(helloguangzhou);
	t.detach();
	s.detach();
return 0;
}

输出只有几行甚至没有输出,因为子线程正在执行还没有执行完,主线程就结束了,所有看不到输出。

hello guangzhou
 hello guangzhou

如果在return 之前加一句代码,让主线程延迟结束,即可看到完整输出。

std::thread t(hellowworld);
	
	std::thread s(helloguangzhou);
	t.detach();
	s.detach();
	std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;

输出结果

hello world hello guangzhou
 hello guangzhou
 hello guangzhou
 hello guangzhou
 hello world
 hello world
 hello world

 hello guangzhou
 hello guangzhou
 hello world
 hello world hello guangzhou

 hello world
 hello guangzhou
 hello world
 hello world
 hello guangzhou
 hello world
 hello guangzhou

猜你喜欢

转载自blog.csdn.net/weixin_43448686/article/details/106554546