现在的位置: 首页 > 综合 > 正文

1.5 线程同步–读写锁

2014年02月05日 ⁄ 综合 ⁄ 共 1950字 ⁄ 字号 评论关闭

目录

一.函数:
1.读写锁的初始化与销毁:

#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
                                             const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

Both return: 0 if OK, error number on failure
2.读写锁的加锁与解锁:
#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);         //加读锁
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);        //加写锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);     
//尝试加读锁,不成功返回EBUSY
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);    //尝试加写锁,不成功返回EBUSY
All return: 0 if OK, error number on failure
二.重点
三.例子:

注意,缺少错误检查

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

int gvar = 0;
pthread_rwlock_t grwlock;

void * thr_fn(void *arg)
{
    int var,i;
    pthread_t tid = pthread_self();
    for(i=0;i<5;i++)
    {
        pthread_rwlock_rdlock(&grwlock);
        printf("tid:%lu,printf gvar=%d\n",tid,gvar);
        pthread_rwlock_unlock(&grwlock);
        usleep(3000);

        pthread_rwlock_wrlock(&grwlock);
        var = gvar;
        var++;
        usleep(2000);
        gvar = var;
        printf("tid:%lu,gvar add one\n",tid);
        pthread_rwlock_unlock(&grwlock);
        usleep(1000);
    }
    pthread_exit((void *)0);
}

int main()
{
    pthread_t tid1,tid2;

    pthread_rwlock_init(&grwlock,NULL);

    pthread_create(&tid1,NULL,thr_fn,NULL);
    pthread_create(&tid2,NULL,thr_fn,NULL);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    printf("main end,gvar=%d\n",gvar);
    pthread_rwlock_destroy(&grwlock);

    return 0;
}

运行:
root@ubuntu1:~/11# ./a.out
tid:3076209520,printf gvar=0
tid:3067816816,printf gvar=0
tid:3076209520,gvar add one
tid:3067816816,gvar add one
tid:3076209520,printf gvar=2
tid:3067816816,printf gvar=2
tid:3076209520,gvar add one
tid:3067816816,gvar add one
tid:3076209520,printf gvar=4
tid:3067816816,printf gvar=4
tid:3076209520,gvar add one
tid:3067816816,gvar add one
tid:3076209520,printf gvar=6
tid:3067816816,printf gvar=6
tid:3076209520,gvar add one
tid:3067816816,gvar add one
tid:3076209520,printf gvar=8
tid:3067816816,printf gvar=8
tid:3076209520,gvar add one
tid:3067816816,gvar add one
main end,gvar=10
root@ubuntu1:~/11#

抱歉!评论已关闭.