#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);
    }
}

c 读写锁 -demo

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2021-06-16
猜你喜欢
  • 2021-11-14
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
  • 2021-07-18
  • 2021-09-07
  • 2022-12-23
相关资源
相似解决方案