下面是一个示例代码,演示了在Linux下使用多线程和标准库函数中的 lseek
和 write
系统调用来读取同一个文件:
#include <iostream>
#include <fstream>
#include <thread>
#include <unistd.h> // 包含 lseek 函数的头文件
#include <fcntl.h> // 包含 open 函数的头文件
void writeToFile(const std::string& filename, const std::string& data)
{
int fd = open(filename.c_str(), O_WRONLY | O_APPEND);
if (fd != -1)
{
off_t pos = lseek(fd, 0, SEEK_END); // 获取当前文件偏移量
if (pos != -1)
{
ssize_t n = write(fd, data.c_str(), data.length()); // 写入数据
if (n == -1) {
std::cerr << "Write error" << std::endl;
}
}
close(fd);
}
}
int main()
{
const std::string filename = "output.txt";
// 创建多个线程来同时写入数据
std::thread t1(writeToFile, filename, "Thread 1\n");
std::thread t2(writeToFile, filename, "Thread 2\n");
std::thread t3(writeToFile, filename, "Thread 3\n");
// 等待所有线程结束
t1.join();
t2.join();
t3.join();
return 0;
}
上述代码创建了三个线程 t1
、t2
和 t3
,它们同时调用 writeToFile()
函数将数据写入同一个文件。在 writeToFile()
函数中,我们使用了 open
函数打开文件,并通过 lseek
函数获取当前的文件偏移量,然后使用 write
函数写入数据。请确保你对文件的读写权限正确设置,并注意并发访问同一文件时需要进行合适的互斥操作,以避免数据竞争问题。
内容由零声教学AI助手提供,问题来源于学员提问