0
点赞
收藏
分享

微信扫一扫

c++11使用容器管理线程对象

泠之屋 2022-02-01 阅读 52
#include <iostream>
#include <string>
using namespace std;
void run(int a){
	std::cout << a << std::endl;
	std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
}

int main()
{
	std::vector<std::thread> obj;
	//没有使用push_back,省略了先构造再移动的操作
	for (int i = 0; i < 5; i++) {
		obj.emplace_back(run, i);
	}
	for (auto it = obj.begin(); it != obj.end(); it++) {
		it->join();
	}
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	return 0;
}

在这里插入图片描述
可以看到,那个线程先执行是不确定的。

举报

相关推荐

0 条评论