C++ multithreading learning (five, container batch creation thread and read-only data sharing)

Table of contents

1. Create threads in batches through containers

Why is there confusion in cout in multithreading

reason:

2. Data sharing

read only


1. Create threads in batches through containers

Why is there confusion in cout in multithreading

Regarding the confusion caused by printing cout, the solution is very simple, just use print.

reason:

When cout outputs, it involves the buffering mechanism of the stream, that is, the data will be cached in the memory first, and then output to the terminal at one time. In a multi-threaded environment, each thread may cache data in its own memory first, and then output it uniformly, resulting in confusion in the order of output.

The printf function directly outputs data to the terminal every time it is printed, without buffering, so there will be no confusion.

#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;
}

2. Data sharing

read only

Stable and safe, no special treatment is required, just read directly.

#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;
}


 

Guess you like

Origin blog.csdn.net/q244645787/article/details/131563912