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