ZBLOG

Linux下多线程使用标准库中的lseek + write系统调用读取同一个文件示例

下面是一个示例代码,演示了在Linux下使用多线程和标准库函数中的 lseekwrite 系统调用来读取同一个文件:

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

上述代码创建了三个线程 t1t2t3,它们同时调用 writeToFile() 函数将数据写入同一个文件。在 writeToFile() 函数中,我们使用了 open 函数打开文件,并通过 lseek 函数获取当前的文件偏移量,然后使用 write 函数写入数据。请确保你对文件的读写权限正确设置,并注意并发访问同一文件时需要进行合适的互斥操作,以避免数据竞争问题。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=3855

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?