pthread_rwlock_t 使用demo

本文展示了如何在C++中使用pthread库实现线程同步,通过读写锁控制多个读者和写者对共享资源的访问,确保线程安全。作者还演示了如何用CMake构建和链接线程程序。
摘要由CSDN通过智能技术生成
#include <pthread.h>
#include <stdio.h>
#include <time.h>  // for nanosleep

// ...

// 定义读写锁
pthread_rwlock_t rwlock;

void* reader(void* arg) {
    while (1) {
        pthread_rwlock_rdlock(&rwlock);
        printf("Reader %ld reading...\n", (long)arg);
        pthread_rwlock_unlock(&rwlock);

        struct timespec sleepTime;
        sleepTime.tv_sec = 0;
        sleepTime.tv_nsec = 500000000;  // 500 milliseconds

        nanosleep(&sleepTime, NULL);
    }
}

void* writer(void* arg) {
    while (1) {
        pthread_rwlock_wrlock(&rwlock);
        printf("Writer %ld writing...\n", (long)arg);
        pthread_rwlock_unlock(&rwlock);

        struct timespec sleepTime;
        sleepTime.tv_sec = 1;  // 1 second
        sleepTime.tv_nsec = 0;

        nanosleep(&sleepTime, NULL);
    }
}


int main() {
    pthread_t readers[3], writers[2];

    // 初始化读写锁
    pthread_rwlock_init(&rwlock, NULL);

    // 创建读者线程
    for (long i = 0; i < 3; ++i) {
        pthread_create(&readers[i], NULL, reader, (void*)i);
    }

    // 创建写者线程
    for (long i = 0; i < 2; ++i) {
        pthread_create(&writers[i], NULL, writer, (void*)i);
    }

    // 等待线程结束
    for (long i = 0; i < 3; ++i) {
        pthread_join(readers[i], NULL);
    }

    for (long i = 0; i < 2; ++i) {
        pthread_join(writers[i], NULL);
    }

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

    return 0;
}
cmake_minimum_required(VERSION 3.12)
project(ThreadExample)

# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 11)

# 添加可执行文件
add_executable(ThreadExample rwlock.cpp)

# 查找线程库
find_package(Threads REQUIRED)

# 链接线程库
target_link_libraries(ThreadExample PRIVATE Threads::Threads)

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值