线程——thread exercise about file

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

 


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值