线程与读写锁

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_rwlock_t lock;

void print(char *p,int count){
	if(NULL == p)
		return ;
	for(;count>0;count--)
		puts(p);
	return ;
}

void *write1(void *arg)
{
    pthread_rwlock_wrlock(&lock);
    print("write1",5);
    pthread_rwlock_unlock(&lock);

    return NULL;
}

void *read1(void *arg)
{
    pthread_rwlock_rdlock(&lock);
    print("read1",5);
    pthread_rwlock_unlock(&lock);
    return NULL;
}

void *read2(void *arg)
{
    pthread_rwlock_rdlock(&lock);
    print("read2",5);
    pthread_rwlock_unlock(&lock);
    return NULL;
}

int main(void)
{
    pthread_t   th1,th2,th3;
    int         ret = 0;

    ret = pthread_rwlock_init(&lock,NULL);
    if( ret != 0 )
    {
        perror("pthread_rwlock_init");
        return -1;
    }

    ret = pthread_create(&th1,NULL,read1,NULL);
    if( ret != 0 )
    {
        perror("read1 ");
        return -2;
    }

    usleep(2000);

    ret = pthread_create(&th2,NULL,write1,NULL);
    if( ret != 0 )
    {
        perror("write1 ");
        return -3;
    }

    usleep(2000);

    ret = pthread_create(&th3,NULL,read2,NULL);
    if( ret != 0 )
    {
        perror("read2 ");
        return -4;
    }

    pthread_join(th1,NULL);
    pthread_join(th2,NULL);
    pthread_join(th3,NULL);
    pthread_rwlock_destroy(&lock);
    return 0;
}
  • 读写锁特点:

      1)多个读者可以同时进行读
      2)写者之间必须互斥
      3)写者与读者之间互斥
      4 ) 写者优先于读者(唤醒时优先考虑写者)
    
  • 互斥锁特点

      1 ) 一次只能一个线程拥有互斥锁,其他线程只有等待
    
  • 读写锁实现了互斥锁

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值