题目:有四个线程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....
D:4 1 2 3 4 1....
三种锁策略耗时不同,第二种最快,循环两百万次耗时在五十多秒(win10+VC2017),第一种是第二种的两倍耗时
c++11代码:
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <string>
#include <thread>
#include <cstdio>
#include <ctime>
#include <map>
const int loop = 500000*4;
std::mutex ml;
int flag;
std::condition_variable cond;
std::string filestr[4];
//锁定在不同写文件上,而不是整个写操作,耗时缩短一倍
std::map<int, int> wf{{0,0},{1,1},{2,2},{3,3} };
std::mutex m[4];
/*
//锁定在整个操作期间,每个线程依次(flag)排队等候操作权,规定线程执行时只能依次进行
void writetofile(int num)
{
std::string writenum = std::string{ char(num + 1+48) };
int fileid = num;
for (int i = 0; i < loop; i++)
{
std::unique_lock<std::mutex> ulock(ml);//锁住了对所有文件的写操作,并没有实现不同线程对不同文件的同时访问
while(flag != num)
cond.wait(ulock);
//std::cout <<flag <<":" << writenum << " ";
filestr[fileid].append(writenum+" ");
fileid = (fileid + 3) % 4;//线程局部变量,仅是在顺序写的时候,可控制写哪个文件
flag = (flag + 1) % 4; //全局变量,控制线程在某个文件上的顺序写,
cond.notify_all();
}
}*/
void writetofile(int num)
{
std::string writenum = std::string{ char(num + 1 + 48) };
int fileid = num;
for (int i = 0; i < loop; i++)
{
//锁定在不同写文件上,而不是整个写操作,耗时缩短一倍
std::unique_lock<std::mutex> ulock(m[fileid]);//四个锁,对不同文件使用,
while(wf[fileid] != num)
cond.wait(ulock);
//std::cout <<flag <<":" << writenum << " ";
filestr[fileid].append(writenum+" ");
wf[fileid] = (wf[fileid] + 1)%4;
cond.notify_all();
ulock.unlock();
fileid = (fileid + 3) % 4;//线程局部变量,仅是在顺序写的时候,可控制写哪个文件
flag = (flag + 1) % 4; //全局变量,控制线程在某个文件上的顺序写,
}
}
/*
void writetofile(int num)
{
std::string writenum = std::string{ char(num + 1 + 48) };
int fileid = num;
for (int i = 0; i < loop; i++)
{//对四个文件锁定,各线程执行顺序没有规定
std::unique_lock<std::mutex> ulock(ml);
while (wf[fileid] != num)
cond.wait(ulock);
//std::cout <<flag <<":" << writenum << " ";
filestr[fileid].append(writenum + " ");
wf[fileid] = (wf[fileid] + 1) % 4;
cond.notify_all();
ulock.unlock();
fileid = (fileid + 3) % 4;//线程局部变量,仅是在顺序写的时候,可控制写哪个文件
flag = (flag + 1) % 4; //全局变量,控制线程在某个文件上的顺序写,
}
}*/
int main(int argc, char *argv[])
{
long begin = std::clock();
//flag = atoi(argv[1]);
std::thread first(writetofile, 0);
std::thread second(writetofile, 1);
std::thread third(writetofile, 2);
std::thread four(writetofile, 3);
//writetofile(0);
first.join();
second.join();
third.join();
for(auto &f : filestr)
{
//std::cout << f<<std::endl;
}
long end = std::clock();
long time = (end - begin)*1000 / CLOCKS_PER_SEC;
std::cout << "finished " <<end << " " <<begin << " " << time <<std::endl;
system("pause");
return 0;
}