建立两线程,向文件内写入

本文介绍如何在Python中通过创建两个线程,实现并发地向同一个文件写入数据,探讨线程同步问题及其解决方案,确保数据的一致性和文件的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

pthread_mutex_t mutex;
void * my_thread1(void *arg)
{
    int fd = *((int *)arg);

    while(1)
    {
        pthread_mutex_lock(&mutex);
        write(fd,"hello",5);
        write(fd,"world",5);
        write(fd,"\n",1);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

void * my_thread2(void *arg)
{
    int fd = *((int *)arg);

    while(1)
    {
        pthread_mutex_lock(&mutex);
        write(fd,"hhhhh",5);
        write(fd,"wwwww",5);
        write(fd,"\n",1);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

int main()
{
    int fd = open("b.txt",O_CREAT | O_RDWR, 0644);
    if(fd == -1)
    {
        perror("open file error!");
        exit(1);
    }

    pthread_t id1;
    pthread_t id2;

    pthread_create(&id1,NULL,my_thread1,(void *)&fd);
    pthread_create(&id2,NULL,my_thread2,(void *)&fd);

    pthread_join(id1,NULL);
    pthread_join(id2,NULL);

    return 0;
}

运行结果:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值