线程锁的第一个版本
#include <thread>
#include <string>
#include <mutex>
#include <iostream>
using namespace std;std::mutex mu;void shared_print(string msg, int id)
{mu.lock();cout << msg.c_str() << id << endl;mu.unlock();
}void function_1() {for (int i = 0; i>-100; i--)shared_print(string("From t1: "), i);
}int main() {std::thread t1(function_1);for (int i = 0; i>-100; i--)shared_print(string("From main: "), i);t1.join();return 0;
}
线程锁的第二个版本,使用lock_guard
#include <thread>
#include <string>
#include <mutex>
#include <fstream>using namespace std;std::mutex mu;class LogFile {std::mutex m_mutex;ofstream f;
public:LogFile(){f.open("log.txt");}void shared_print(string id, int value) {std::lock_guard<mutex> locker(m_mutex);f << "From " << id << ": " << value << endl;}};void function_1(LogFile& log)
{for (int i = 0; i < 100; i++)log.shared_print(string("From t1: "), i);
}int main() {LogFile log;std::thread t1(function_1, std::ref(log));for (int i = 0; i > -100; i--)log.shared_print(string("From main: "), i);t1.join();return 0;
}