C++实现多线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MOU_IT/article/details/88724199

1、helloworld

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

std::mutex display_mutex;          //使用互斥锁

void foo(int i){	
	std::thread::id this_id = std::this_thread::get_id();
	display_mutex.lock();    //加锁
	std::cout << "thread_func: id = " << this_id << ", " << i << std::endl;
	display_mutex.unlock();  //解锁
}

void MultiThread()
{
	for (int i = 0; i < 4; i++)
	{
		std::thread thread(foo, i);
		thread.detach();	
		std::cout <<std::endl<< "main:" << std::endl;
	}
	getchar();
	return;
}

   输出: 

thread_func: id = 5960
, main:
0
thread_func: id = 13540, 1

main:

main:
thread_func: id = 7684, 2
thread_func: id = 14252, 3

main:

2、两种方等待线程结束的方式:detach、join

  (1)detach在这里表示启动的线程自己在后台运行,当前的代码继续运行,不等待新的线程结束;

  (2)join的方式实在线程运行完成后再继续往下运行,所以如果对之前的代码再做修改如下:

void MultiThread()
{
	for (int i = 0; i < 4; i++)
	{
		std::thread thread(foo, i);
		thread.join();	
		std::cout <<std::endl<< "main:" << std::endl;
	}
	getchar();
	return;
}

   输出:

thread_func: id = 5692, 0

main:
thread_func: id = 7228, 1

main:
thread_func: id = 3368, 2

main:
thread_func: id = 8180, 3

main:

参考:https://www.jianshu.com/p/835f4d37395b

猜你喜欢

转载自blog.csdn.net/MOU_IT/article/details/88724199