第08章 读写锁

8.1 概述

  • 读写锁的分配规则如下:
    • 只要没有某个线程持有该锁用于写,任意数目的线程可持有用于读
    • 没有线程持有用于写时,才能分配用于写

8.2 获取与释放读写锁

#include <pthread.h>

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

8.3 读写锁的属性

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
        const pthread_rwlockattr_t *restrict attr);
int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);
int pthread_rwlockattr_init(pthread_rwlockattr_t *attr);
int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *
              restrict attr, int *restrict pshared);
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr,
              int pshared);

8.5 线程的取消

  • 在另一篇博客已经讲了,就不在赘述
  • 下面是unp给的一个例子
/* include main */
#include    "unpipc.h"
#include    "pthread_rwlock.h"

pthread_rwlock_t    rwlock = PTHREAD_RWLOCK_INITIALIZER;
pthread_t   tid1, tid2;
void     *thread1(void *), *thread2(void *);

int
main(int argc, char **argv)
{
    void    *status;

    Set_concurrency(2);
    Pthread_create(&tid1, NULL, thread1, NULL);
    sleep(1);       /* let thread1() get the lock */
    Pthread_create(&tid2, NULL, thread2, NULL);

    Pthread_join(tid2, &status);
    if (status != PTHREAD_CANCELED)
        printf("thread2 status = %p\n", status);
    Pthread_join(tid1, &status);
    if (status != NULL)
        printf("thread1 status = %p\n", status);

    printf("rw_refcount = %d, rw_nwaitreaders = %d, rw_nwaitwriters = %d\n",
           rwlock.rw_refcount, rwlock.rw_nwaitreaders,
           rwlock.rw_nwaitwriters);
    Pthread_rwlock_destroy(&rwlock);

    exit(0);
}

void *
thread1(void *arg)
{
    Pthread_rwlock_rdlock(&rwlock);
    printf("thread1() got a read lock\n");
    sleep(3);       /* let thread2 block in pthread_rwlock_wrlock() */
    pthread_cancel(tid2);
    sleep(3);
    Pthread_rwlock_unlock(&rwlock);
    return(NULL);
}

void *
thread2(void *arg)
{
    printf("thread2() trying to obtain a write lock\n");
    Pthread_rwlock_wrlock(&rwlock);
    printf("thread2() got a write lock\n"); /* should not get here */
    sleep(1);
    Pthread_rwlock_unlock(&rwlock);
    return(NULL);
}
/* end main */

猜你喜欢

转载自blog.csdn.net/qq_36337149/article/details/81296933