C++ マルチスレッド学習 (5、コンテナーのバッチ作成スレッドと読み取り専用データ共有)

目次

1. コンテナを通じてバッチでスレッドを作成する

マルチスレッドで cout が混乱するのはなぜですか

理由:

2. データ共有

読み取り専用


1. コンテナを通じてバッチでスレッドを作成する

マルチスレッドで cout が混乱するのはなぜですか

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

2. データ共有

読み取り専用

安定かつ安全で、特別な処理は必要ありません。直接読むだけです。

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


 

おすすめ

転載: blog.csdn.net/q244645787/article/details/131563912