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