题目:有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
A:1 2 3 4 1 2....
B:2 3 4 1 2 3....
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();
}