#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
class locfFile
{
public:
locfFile(){
f.open("log.txt"); //构造函数打开log.tex文件
}
void shared_print(std::string id, int value){
std::lock_guard<std::mutex> loker(m_mutex);
f << "from" << id << ":" << value << std::endl;
}
protected:
private:
std::mutex m_mutex;
std::ofstream f; //被m_mutex保护的对象
};
void function_1(locfFile& log){
for (int i = 0; i > -100; i--){
log.shared_print("from t1:" ,i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
locfFile log;
std::thread t1(function_1,std::ref(log));
for (int i = 0; i < 100; i++)
log.shared_print("from main:" ,i);
t1.join();
system("PAUSE");
return 0;
}
效果:
fromfrom t1::0
fromfrom main::0
fromfrom t1::-1
fromfrom main::1
fromfrom t1::-2
fromfrom main::2
fromfrom t1::-3
fromfrom main::3
fromfrom t1::-4
fromfrom main::4
fromfrom t1::-5
fromfrom main::5
fromfrom t1::-6
fromfrom main::6
fromfrom t1::-7
fromfrom main::7
fromfrom t1::-8
fromfrom main::8
fromfrom t1::-9
fromfrom main::9
fromfrom t1::-10
..........