读写锁

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

int s_num = 0;
pthread_rwlock_t slock;

void *thread_fun(void *arg)
{
        while(1)
        {
                pthread_rwlock_rdlock(&slock);
                printf("======> %ld thread s_num=%d\n", reinterpret_cast<long>(arg), s_num);
                pthread_rwlock_unlock(&slock);
                usleep(100000);
        }
        return NULL;
}

int main(int argc, char *argv[])
{
        pthread_rwlock_init(&slock, NULL);
        for (long i=0; i<5; i++)
        {
                pthread_t th;
                int ret = pthread_create(&th, NULL,
                          thread_fun, reinterpret_cast<void *>(i));
                if (ret < 0)
                {
                        printf("pthread_create error\n");
                        return 0;
                }
                pthread_detach(th);
        }

        while(1)
        {
                pthread_rwlock_wrlock(&slock);
                printf("======>write s_num=%d\n", s_num++);
                pthread_rwlock_unlock(&slock);
                usleep(500000);
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值