线程——thread exercise about file

本文深入探讨了并发编程技术在文件操作中的应用,通过使用互斥量和线程实现了高效的数据处理流程。详细介绍了如何利用多线程并发读取与修改文件内容,并在代码实现中展示了关键步骤与技巧。

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

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define THRNUM 20 
#define FNAME "/tmp/out"
#define LINESIZE 1024

#if 0
    static pthread_mutex_t foo_mutex = PTHREAD_MUTEX_INITIALIZER;

    void foo()
    {
        pthread_mutex_lock(&foo_mutex);
            /* Do work. */
        pthread_mutex_unlock(&foo_mutex);
    }

#endif


static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

static void * thr_add(void *p)
{
 FILE *fp;
 char linebuf[LINESIZE];
 
 fp = fopen(FNAME,"r+");
 if(fp == NULL)
 {
  perror("fopen()");
  exit(1);
 }
// 互斥量加锁 (原子化)
 pthread_mutex_lock(&mut); //阻塞——unlock
 fgets(linebuf,LINESIZE,fp);
 fseek(fp,0,SEEK_SET);
// sleep(1);
 fprintf(fp,"%d\n",atoi(linebuf)+1);
 fclose(fp);
 pthread_mutex_unlock(&mut);

 pthread_exit(NULL);
}

int main()
{
 pthread_t tid[THRNUM];
 int i,err;

 for(i = 0; i < THRNUM; i++)
 {

  err = pthread_create(tid+i,NULL,thr_add,NULL);
  if(err) 
  {
   fprintf(stderr,"pthread_create():%s\n",strerror(err));
   exit(1);
  }

 }


 for(i = 0; i < THRNUM; i++)
  pthread_join(tid[i],NULL);

 pthread_mutex_destroy(&mut);

 exit(0);
}

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值