c 读写锁 -demo

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

void readFunc();
void writeFunc();

int data = 0;
pthread_rwlock_t rwlock;

int main() {
    pthread_rwlock_init(&rwlock, NULL);
    pthread_t readThread;
    pthread_t writeThread;
    pthread_t readThread1;
    pthread_create(&readThread, NULL, readFunc, NULL);
    pthread_create(&writeThread, NULL, writeFunc, NULL);
    pthread_create(&readThread1, NULL, readFunc, NULL);

    pthread_join(readThread, NULL);
    pthread_join(writeThread, NULL);
    pthread_join(readThread1, NULL);

    pthread_rwlock_destroy(&rwlock);

    return 0;
}

void readFunc() {
    while (1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("read data:%d, tid:%d\n", data, pthread_self());
        sleep(1);
        pthread_rwlock_unlock(&rwlock);
    }
}

void writeFunc() {
    while (1) {
        pthread_rwlock_wrlock(&rwlock);
        printf("write data:%d, tid:%d\n", data, pthread_self());
        data++;
        sleep(2);
        pthread_rwlock_unlock(&rwlock);
    }
}

猜你喜欢

转载自www.cnblogs.com/luckygxf/p/12370137.html