C语言下面的一个多线程读写锁例子

发布时间 2024-01-02 11:12:47作者: He_LiangLiang

这是一个C语言多线程读写锁的例子。

创建了10个线程,线程对一个全局变量做自减操作。减到0之后线程退出。

每个自减线程里面添加了 写锁,避免了数据竞争的情况。

 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdint.h>
#include <stddef.h>


#define THREAD_COUNT 10

// 全局变量
int iCount = 100;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

// 线程函数
void *decrementThread(void *arg) {
    int threadId = *((int *)arg);

    while (1) {
        // 加写锁
        pthread_rwlock_wrlock(&rwlock);

        if (iCount > 0) {
            iCount--;
            printf("Thread %d: iCount = %d\n", threadId, iCount);
        }

        // 解写锁
        pthread_rwlock_unlock(&rwlock);

        // 判断是否终止
        if (iCount <= 0) {
            break;
        }
    }

    return NULL;
}

int main() {
    pthread_t threads[THREAD_COUNT];
    int threadIds[THREAD_COUNT];

    // 初始化读写锁
    if (pthread_rwlock_init(&rwlock, NULL) != 0) {
        perror("Failed to initialize rwlock");
        exit(EXIT_FAILURE);
    }

    // 创建并启动线程
    for (int i = 0; i < THREAD_COUNT; i++) {
        threadIds[i] = i + 1;
        if (pthread_create(&threads[i], NULL, decrementThread, (void *)&threadIds[i]) != 0) {
            perror("Failed to create thread");
            exit(EXIT_FAILURE);
        }
    }

    // 等待所有线程结束
    for (int i = 0; i < THREAD_COUNT; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            perror("Failed to join thread");
            exit(EXIT_FAILURE);
        }
    }

    // 销毁读写锁
    pthread_rwlock_destroy(&rwlock);

    // 打印最终结果
    printf("Final iCount = %d\n", iCount);

    return 0;
}

// gcc program.c -o program.bin -pthread