1.如果是读取时间,为了增加线程的运行速度,应该让所有线程可同一时刻读取数据。比如,对于一个全局变量,应该让所有的子线程在同一时刻可对其进行读取,因为读取数据,并不会改变原来的数据,不会影响到数据的安全性。
2.利用读写锁可完成上述的操作。当资源或代码段被上了读锁时,其他的线程亦可以访问被上锁的资源、代码。而当资源被上了读写锁时,其他的线程此时不能访问被上锁的资源,此时的读写锁和互斥锁具有相同的功能。
3.利用读写锁设计的访问全局变量的程序代码如下:
/*读写锁的简单案例*/
//5个线程同时访问一个全局变量,其中两个进行写操作,三个进行读操作
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int number = 0;
//创建读写锁
pthread_rwlock_t rwlock;
void *wwork(void *arg)
{
while(1)
{
//上读写锁
//pthread_rwlock_rwlock(&rwlock);
pthread_rwlock_wrlock(&rwlock);
number++;
printf("++write,tid : %ld, number : %d\n",pthread_self(),number);
//解读写锁
pthread_rwlock_unlock(&rwlock);
usleep(1000);
}
return NULL;
}
void *rwork(void *arg)
{
while(1)
{
//上读写锁
pthread_rwlock_rdlock(&rwlock);
printf("===read,tid : %ld, number : %d\n",pthread_self(),number);
//解读写锁
pthread_rwlock_unlock(&rwlock);
usleep(1000);
}
return NULL;
}
int main()
{
//初始话读写锁
pthread_rwlock_init(&rwlock,NULL);
//创建线程
pthread_t wtid[2],rtid[3];
for(int i = 0; i < 2;i++)
{
pthread_create(&wtid[i],NULL,wwork,NULL);
}
for(int i = 0;i < 3;i++)
{
pthread_create(&rtid[i],NULL,rwork,NULL);
}
//设置线程分离,在子线程结束后,自动回收资源,非阻塞
for(int i = 0;i < 2;i++)
{
pthread_detach(wtid[i]);
}
for(int i = 0;i < 3;i++)
{
pthread_detach(rtid[i]);
}
//退出主线程
pthread_exit(NULL);
//释放读写锁资源
pthread_rwlock_destroy(&rwlock);
return 0;
}
4.运行结果:
5.总结:读写锁让所有的线程同时读取共享资源,而写数据(修改数据)时,读写锁的功能与互斥锁一样。通过读写锁可提高线程的运行速度。