目录

一、通过容器批量创建线程

为什么多线程中cout会出现混乱

原因:

二、数据共享

只读


一、通过容器批量创建线程

为什么多线程中cout会出现混乱

关于打印cout会导致混乱解决方法很简单,用print即可。

原因:

cout在进行输出时,涉及到了流的缓冲机制,即数据先会被缓存在内存中,然后再一次性输出到终端。而在多线程环境下,每个线程都有可能先将数据缓存在自己的内存中,然后再统一输出,导致输出的顺序混乱。

printf函数在每次打印时直接将数据输出到终端,不需要进行缓冲,因此不会出现混乱的情况。

#include <iostream>
#include <cstdio>
#include <thread>
#include <vector>
using namespace std;
void IndexPrint(int index)
{
	//cout << "线程序号:" << index << endl;
	printf("线程序号:%d\n", index);//用printf不会混乱
}
int main()
{
	vector<thread*> t;
	for (int i = 0; i < 10; i++)
	{
		t.push_back(new thread(IndexPrint,i));//将创建出来的线程放到容器中去
	}
	for (auto v:t)//通过迭代器做指针访问
	{
		v->join();//汇合一下
	}
	cout << "end" << endl;
	return 0;
}

二、数据共享

只读

稳定安全,不需要特殊处理,直接读取即可。

#include <iostream>
#include <cstdio>
#include <thread>
#include <vector>
using namespace std;
vector<int> MoreData{ 1,2,3 };
void IndexPrint(int index)
{
	printf("线程序号:%d\n", index);//用printf不会混乱
	for (auto p:MoreData)
	{
		printf("%d\n", p);
	}
}


int main()
{
	vector<thread*> t;
	for (int i = 0; i < 10; i++)
	{
		t.push_back(new thread(IndexPrint, i));
	}
	for (auto a:t)
	{
		a->join();
	}
	printf("end\n");


	
	return 0;
}


 

07-06 01:37