Linux 读写锁

Linux 读写锁_第1张图片

读写锁是一把锁Linux 读写锁_第2张图片

/*
    读写锁的类型 pthread_rwlock_t
    pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
    int pthread_rwlock_destory(pthread_rwlock_t *rwlock);
    int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
*/

#include
#include
#include
#include

int num = 1;
pthread_rwlock_t rwlock;
void* writeNum(void * arg) {
    while(1) {
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("++write, tid: %ld, num:%d\n", pthread_self(), num);
        pthread_rwlock_unlock(&rwlock);
        usleep(500);   
    }
}
void* readNum(void * arg) {
    while(1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("==read, tid: %ld, num:%d\n", pthread_self(), num);
        pthread_rwlock_unlock(&rwlock);
        usleep(500);   
    }
}


int main() {

    pthread_rwlock_init(&rwlock, NULL);
    pthread_t wtid[3];
    pthread_t rtid[5];
    for(int i = 0; i < 3; i++) {
        pthread_create(&wtid[i], NULL, writeNum, NULL);
    }
    for(int i = 0; i < 5; i++) {
        pthread_create(&rtid[i], NULL, readNum, NULL);
    }

    for(int i = 0; i < 3; i++) {
        pthread_detach(wtid[i]);
    }
    for(int i = 0; i < 5; i++) {
        pthread_detach(rtid[i]);
    }
    
    pthread_exit(NULL);

    pthread_rwlock_destroy(&rwlock);

    return 0;

}

你可能感兴趣的:(Linux线程管理,Linux编程入门,linux,运维,服务器)