您的位置:首页 > 其它

多线程学习系列三 多线程实现读者和写者问题

2015-08-21 13:24 399 查看
设置读线程是两个,写线程一个,用读写锁实现。

#include<stdio.h>

#include<stdlib.h>

#include<pthread.h>

#define RNUM 2

pthread_rwlock_t lock;

struct Data

{

int a;

float b;

};

struct Data *pdata = NULL;

void *Read(void *num)

{

int i = 0;

while( i++ != 3)

{

pthread_rwlock_rdlock(&lock);

if(pdata == NULL)

printf("reader[%d]:%u is reading data ! data is NULL\n",(int)num,(int)pthread_self());

else

printf("reader[%d]:%u is reading data! data: %d %f \n",(int)num,(int)pthread_self(),pdata->a,pdata->b);

pthread_rwlock_unlock(&lock);

}

return (void *)0;

}

void *Write(void *num)

{

int i = 0;

while(i++ != 3)

{

pthread_rwlock_wrlock(&lock);

if(pdata == NULL)

{

pdata = (struct Data *)malloc(sizeof(struct Data));

pdata->a = 23 + i;

pdata->b = 12.3 + i;

printf("writer:%u is writing data ! %d %f\n",(int)pthread_self(),pdata->a,pdata->b);

}

else

{

free(pdata);

pdata = NULL;

printf("writer:%u writer free the data!\n",(int)pthread_self());

}

pthread_rwlock_unlock(&lock);

}

return (void *)0;

}

int main()

{

pthread_t reader[RNUM];

pthread_t writer;

for(int i=0;i<RNUM;i++)

pthread_create(&reader[i],NULL,Read,(void *)i);

pthread_create(&writer,NULL,Write,NULL);

pthread_join(writer,NULL);

for(int i=0;i<RNUM;i++)

pthread_join(reader[i],NULL);

printf("Main thread:%u is finished!\n",(int)pthread_self());

return 0;

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: