//本文在c++ builder 10.3平台调试通过
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
#include <fstream>
volatile int counter(0); // 定义一个全局变量,当做计数器用于累加
std::mutex mtx; // 用于保护counter的互斥锁
void thrfunc()
{ mtx.lock(); //互斥锁上锁
std::ofstream f;
f.open("d:\\test1.txt", std::ios::app);
if (f)
{ for (int i = 0; i < 10000; i++)
{
counter++;
f << counter << std::endl;
}
f.close();
}
mtx.unlock(); //互斥锁解锁
}
void readFile()
{ mtx.lock(); //互斥锁上锁
while(counter<100000)
{ char buffer[256];
ifstream f;
f.open("d:\\test1.txt", std::ios_base::in);
if (f)
{ while (!f.eof() )
{ f.getline (buffer,100);
std::cout << buffer << std::endl;
}
f.close();
}
else std::cout << "no open" << std::endl;
}
mtx.unlock(); //互斥锁解锁
}
int _tmain(int argc, _TCHAR* argv[])
{
std::thread threads[10];
std::thread thread1;
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(thrfunc); //启动10个线程
thread1 = std::thread(readFile); //启动1个线程
for (auto& th : threads) th.join(); //等待10个线程结束
thread1.join();
// std::cout << "count to " << counter << " successfully \n";
system("pause");
return 0;
}