5,530
社区成员
发帖
与我相关
我的任务
分享
//线程1和线程2交替执行完成文本文件的数据填充。
//线程1完成奇数行的填充,线程2完成偶数行的填充,各填充5遍
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
struct lockData
{
int value;
pthread_mutex_t mutex;
pthread_cond_t cond;
};
typedef struct lockData lockData;
void writefile(int num)
{
FILE *fp;
if( (fp=fopen("demo.txt","a+")) == NULL )
{
printf("Cannot open file, press any key exit!");
getchar();
exit(1);
}
fprintf(fp,"%d\n", num);
fclose(fp);
}
lockData* initThreadData(int arg)
{
lockData *fp;
fp = (lockData*)malloc(sizeof(lockData));
if(fp == NULL)
{
printf("malloc err!\n");
return NULL;
}
int status = 0;
status = pthread_mutex_init(&fp->mutex,NULL);
if(status !=0)
{
printf("mutex init err!");
free(fp);
return NULL;
}
status = pthread_cond_init(&fp->cond,NULL);
if(status != 0)
{
printf("cond init err!\n");
free(fp);
return NULL;
}
fp->value = arg;
return (fp);
}
void *dojob1(void* arg)
{
lockData *data = (lockData*)arg;
while(data->value<=10)
{
pthread_mutex_lock(&data->mutex);
while(data->value %2 == 0) //线程1 写奇数 ,因此,他要写的数据应该 X%2 !=0,假如x%2==0 说明应该等另外一个线程对X做自增操作
pthread_cond_wait(&data->cond,&data->mutex);
writefile(data->value);
data->value +=1;
pthread_cond_signal(&data->cond);
pthread_mutex_unlock(&data->mutex);
}
return (void*)0;
}
void *dojob2(void *arg)
{
lockData *data = (lockData*)arg;
while(data->value <=10)
{
pthread_mutex_lock(&data->mutex);
while(data->value %2 !=0 ) //线程2 写偶数,因此要写的书应该是 X%2==0 ,假如不是,则应该等另外一个线程对X做自增操作
pthread_cond_wait(&data->cond,&data->mutex);
writefile(data->value);
data->value +=1;
pthread_cond_signal(&data->cond);
pthread_mutex_unlock(&data->mutex);
}
return (void*)0;
}
int main()
{
lockData *data = initThreadData(1);
pthread_t id1,id2;
pthread_create(&id1,NULL,dojob1,(void*)data);
pthread_create(&id2,NULL,dojob2,(void*)data);
printf("[thr1:%u] [thr2:%ld]",(unsigned int)id1,(unsigned int)id2);
void* status1 = 0;
void* status2 = 0;
pthread_join(id1,&status1);
pthread_join(id2,&status2);
if(data != NULL)
free(data);
data = NULL;
printf("down!%d %d\n",(long)status1,(long)status2);
return 0;
}
仅供参考,某一种实现!