c语言读写锁,读写锁详解-hededisanan00-ChinaUnix博客

#include

#include

#include

struct my_file

{

int num;

pthread_rwlock_t lock_num;

};

void * write1(void *arg)

{

struct my_file *file_info=(struct my_file *)arg;

pthread_rwlock_wrlock(&file_info->lock_num);

printf("write1:my_file->num:%d,process=%d,thread num:%d\n",file_info->num++,getpid(),pthread_self());

pthread_rwlock_unlock(&file_info->lock_num);

return((void *)1);

}

void *write2(void *arg)

{

struct my_file *file_info=(struct my_file *)arg;

pthread_rwlock_wrlock(&file_info->lock_num);

printf("write2:my_file->num:%d,process=%d,thread num:%d\n",file_info->num++,getpid(),pthread_self());

sleep(3);

pthread_rwlock_unlock(&file_info->lock_num);

return((void *)2);

}

void *read(void *arg)

{

struct my_file *file_info=(struct my_file *)arg;

printf("enter read:\n");

pthread_rwlock_rdlock(&file_info->lock_num);

printf("read:my_file->lock_num:%d,process=%d,thread num:%d\n",file_info->num,getpid(),pthread_self());

pthread_rwlock_unlock(&file_info->lock_num);

printf("after read:\n");

return((void *)3);

}

int main(void)

{

pthread_t th1,th2,th3;

struct my_file *test;

test= (struct my_file *)malloc(sizeof(struct my_file )*1);

if( test == NULL )

{

perror("allocate is failed");

return 0;

}

test->num=0;

pthread_rwlock_init(&test->lock_num,NULL);

int ret;

while(test->num<10)

{

ret==pthread_create(&th1,NULL,write1,test);

if( ret != 0 )

{

perror("pthread1 error");

return 0;

}

usleep(1000);

pthread_create(&th2,NULL,write2,test);

if( ret != 0 )

{

perror("pthread2 error");

return 0;

}

usleep(1000);

pthread_create(&th3,NULL,read,test);

if( ret != 0 )

{

perror("pthread3 error");

return 0;

}

pthread_join(th3,NULL);

pthread_rwlock_destroy(&test->lock_num);

}

free(test);

test=NULL;

return 1;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值