线程与读写锁

#include 

#include 

pthread_rwlock_t lock;

void * write1(void *arg)
{
    pthread_rwlock_wrlock(&lock);
    puts("write1");
    pthread_rwlock_unlock(&lock);

    return((void *)1);
}

void *write2(void *arg)
{
    pthread_rwlock_wrlock(&lock);
    puts("write2");
    pthread_rwlock_unlock(&lock);

    return((void *)2);
}

void *read1(void *arg)
{
    pthread_rwlock_rdlock(&lock);
    puts("read1");
    sleep(10);
    pthread_rwlock_unlock(&lock);
    return((void *)3);
}

void *read2(void *arg)
{
    pthread_rwlock_rdlock(&lock);
    puts("read2");
    pthread_rwlock_unlock(&lock);
    return((void *)3);
}

int main(void)
{
    pthread_t   th1,th2,th3,th4;
    int         ret;
    ret =pthread_create(&th1,NULL,write1,NULL);
    if( ret != 0 )
    {
        perror("pthread1 ");
        return 0;
    }
    usleep(1000);
    ret = pthread_create(&th3,NULL,read1,NULL);
    if( ret != 0 )
    {
        perror("pthread3 ");
        return 0;
    }
    usleep(1000);
    ret = pthread_create(&th4,NULL,read2,NULL);
    if( ret != 0 )
    {
        perror("pthread4 ");
        return 0;
    }
    usleep(1000);
    ret = pthread_create(&th2,NULL,write2,NULL);
    if( ret != 0 )
    {
        perror("pthread2 ");
        return 0;
    }
    pthread_join(th3,NULL);
    pthread_rwlock_destroy(&lock);
    return 1;
}

读写锁特点:

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

互斥锁特点: 
1 ) 一次只能一个线程拥有互斥锁,其他线程只有等待

读写锁实现了互斥锁

你可能感兴趣的:(线程与读写锁)