▶ 使用读写锁来限制同一数据多线程读写。若任何线程拥有读锁,则其他任何请求写锁的线程将阻塞在其写锁函数的调用上;若任何线程拥有写锁,则其他任何请求读锁和写锁的线程将阻塞在其对应的锁函数上,相当于将读与写的互斥量分开,且写入锁的要求更高一些。
● 代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#pragma comment(lib, "pthreadVC2.lib") const int thread = , dataSize = , workCount = ;
int data[dataSize];
pthread_rwlock_t rwlock; void* work(void* rank)
{
const long long localRank = (long long)rank;
int i, readCount, writeCount;
for (i = ; i < workCount; i++)
{
if (rand() % )
{
pthread_rwlock_rdlock(&rwlock);// 读过程,上锁,读取,解锁
data[i];
pthread_rwlock_unlock(&rwlock);
}
else
{
pthread_rwlock_wrlock(&rwlock);// 写过程,上锁,写入,解锁
data[i] = rand();
pthread_rwlock_unlock(&rwlock);
}
}
return nullptr;
} int main()
{
pthread_t pth[thread];
int i;
long long list[thread]; srand();
for (i = ; i < dataSize; data[i++] = rand());
pthread_rwlock_init(&rwlock, nullptr); // 初始化读写锁
for (i = ; i < thread;i++)
{
list[i] = i;
pthread_create(&pth[i], nullptr, work, (void *)list[i]);
}
for (i = ; i < thread; i++)
pthread_join(pth[i], nullptr); // 销毁用完的读写锁
pthread_rwlock_destroy(&rwlock);
printf("\nfinish.\n");
getchar();
return ;
}
● 用到的定义,pthread.h
typedef struct pthread_rwlock_t_ * pthread_rwlock_t; PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock, const pthread_rwlockattr_t *attr);// 初始化已经声明了的读写锁,第二个参数是属性指针 PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock); // 销毁用完了的读写锁 PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock); // 读锁定 PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock); // 写锁定 PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock); // 解锁