解决方案:
为每个线程创建一个日志文件
#include <iostream>
#include <fstream>
#include <thread>
void thread_func(const std::string& log_file) {
std::ofstream log(log_file, std::ios::out | std::ios::app);
if (!log) {
std::cerr << "Could not open log file: " << log_file << std::endl;
return;
}
log << "This is a log message from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t1(thread_func, "log1.txt");
std::thread t2(thread_func, "log2.txt");
t1.join();
t2.join();
return 0;
}