在C++多线程环境下,为了避免文件被多个线程同时访问和覆盖,可以采用以下策略:
#include<iostream>
#include <fstream>
#include <mutex>
#include<thread>
std::mutex file_mutex;
void write_to_file(const std::string& data) {
std::unique_lock<std::mutex> lock(file_mutex);
std::ofstream file("output.txt");
file<< data;
file.close();
lock.unlock();
}
int main() {
std::thread t1(write_to_file, "Thread 1 data");
std::thread t2(write_to_file, "Thread 2 data");
t1.join();
t2.join();
return 0;
}
#include<iostream>
#include <fstream>
#include<thread>
#ifdef _WIN32
#include<windows.h>
#else
#include <fcntl.h>
#include <unistd.h>
#endif
void write_to_file(const std::string& data) {
#ifdef _WIN32
HANDLE hFile = CreateFile("output.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
OVERLAPPED overlapped = {0};
LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped);
#else
int fd = open("output.txt", O_WRONLY | O_CREAT, 0666);
flock(fd, LOCK_EX);
#endif
std::ofstream file("output.txt");
file<< data;
file.close();
#ifdef _WIN32
UnlockFileEx(hFile, 0, MAXDWORD, MAXDWORD, &overlapped);
CloseHandle(hFile);
#else
flock(fd, LOCK_UN);
close(fd);
#endif
}
int main() {
std::thread t1(write_to_file, "Thread 1 data");
std::thread t2(write_to_file, "Thread 2 data");
t1.join();
t2.join();
return 0;
}
std::atomic_flag
或std::atomic<T>
来实现原子操作。请注意,这些策略并不能保证文件内容的一致性。在多线程环境下,你需要确保每个线程都按照正确的顺序执行操作,以避免数据不一致的问题。