多线程输出到多个文件的那个谷歌面试题

题目:有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
A:1 2 3 4 1 2....
B:2 3 4 1 2 3....

C:3 4 1 2 3 4....

#include <vector>
#include <fstream>
#include <thread>
#include <condition_variable>

using namespace std;


fstream file_A("A.txt", fstream::out), file_B("B.txt", fstream::out), file_C("C.txt", fstream::out), file_D("D.txt", fstream::out);

condition_variable cv;
mutex counter_mtx;
int counter = 0;

const int loops = 100;


void synchronize()		{
	unique_lock<mutex> ul(counter_mtx);
	counter++;
	if (counter==4) {
		cv.notify_all();
		counter = 0;
	}else
	cv.wait(ul);
}
void thread_proc_1(){
	for (int i = 0; i < loops; i++){
		file_A << "1";
		synchronize();
	
		file_D << "1";
		synchronize();

		file_C << "1";
		synchronize();

		file_B << "1";
		synchronize();
	}
}
void thread_proc_2(){
	for (int i = 0; i < loops; i++){
		file_B << "2";
		synchronize();

		file_A << "2";
		synchronize();

		file_D << "2";
		synchronize();

		file_C << "2";
		synchronize();
	}
}
void thread_proc_3(){
	for (int i = 0; i < loops; i++){
		file_C << "3";
		synchronize();

		file_B << "3";
		synchronize();

		file_A << "3";
		synchronize();

		file_D << "3";
		synchronize();
	}
}
void thread_proc_4(){
	for (int i = 0; i < loops; i++){
		file_D << "4";
		synchronize();

		file_C << "4";
		synchronize();

		file_B << "4";
		synchronize();

		file_A << "4";
		synchronize();
	}
}

void(*thread_procs[])(void) = { thread_proc_1, thread_proc_2, thread_proc_3, thread_proc_4 };

int main(int argc, _TCHAR* argv[]){
	vector<thread> v;
	for (int i = 0; i < 4; i++)v.push_back(thread(thread_procs[i]));
	for (auto& t : v) t.join();
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值