c 读写锁 -demo

北城以北 提交于 2020-02-27 01:45:25
#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);
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!