在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>
來實現原子操作。請注意,這些策略并不能保證文件內容的一致性。在多線程環境下,你需要確保每個線程都按照正確的順序執行操作,以避免數據不一致的問題。