当前位置: 代码迷 >> 综合 >> C++知识点-线程3-线程锁
  详细解决方案

C++知识点-线程3-线程锁

热度:22   发布时间:2024-01-27 23:25:21.0

线程锁的第一个版本

#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;
}

 

 

  相关解决方案