课时86_读写锁练习
1、要求
3个线程不定时写同一个全局资源,5个线程不定时读同一个全局资源。
2、不加锁
2.1、不加锁代码
#include <stdio.h> //printf对应的头文件
#include <unistd.h> //usleep对应的头文件
#include <pthread.h> //线程对应的头文件
//全局变量
int number;
void* write_func(void* arg)
{
//循环写
while(1)
{
number++;
printf("==write:%lu,%d\n",pthread_self(),number);
usleep(500);
}
return NULL;
}
void* read_func(void* arg)
{
while(1)
{
printf("&&read:%lu,%d\n",pthread_self(),number);
usleep(500);
}
return NULL;
}
//主函数
int main()
{
//子线程ID
pthread_t pthid[8];
//创建3个写线程
for(int i = 0; i < 3; ++i)
{
pthread_create(&pthid[i],NULL,write_func,NULL);
}
//创建5个读线程
for(int i = 3; i < 8; ++i)
{
pthread_create(&pthid[i],NULL,read_func,NULL);
}
//阻塞,资源回收
for(int i = 0; i < 8; ++i)
{
pthread_join(pthid[i],NULL);
}
return 0;
}
2.2、不加锁代码执行结果
&&read:140000195254016,15932
==write:140000228824832,15931
结果分析:
打印number顺序应该从小到大,写操作number=15931后,没有及时打印printf("==write:%lu,%d\n",pthread_self(),number);
然后读read到的是写入后的数值15931。如果在printf("==write:%lu,%d\n",pthread_self(),number);
代码后解锁,就不会出现打印不及时的情况。
3、加读写锁
3.1、加读写锁代码
#include <stdio.h> //printf对应的头文件
#include <unistd.h> //usleep对应的头文件
#include <pthread.h> //线程对应的头文件
//全局变量
int number;
//创建读写锁
pthread_rwlock_t lock;
void* write_func(void* arg)
{
//循环写
while(1)
{
//加写锁
pthread_rwlock_wrlock(&lock);
number++;
printf("==write:%lu,%d\n",pthread_self(),number);
//解锁
pthread_rwlock_unlock(&lock);
usleep(50);
}
return NULL;
}
void* read_func(void* arg)
{
while(1)
{
//加读锁
pthread_rwlock_rdlock(&lock);
printf("&&read:%lu,%d\n",pthread_self(),number);
//解锁
pthread_rwlock_unlock(&lock);
usleep(50);
}
return NULL;
}
//主函数
int main()
{
//子线程ID
pthread_t pthid[8];
//初始化读写锁
pthread_rwlock_init(&lock,NULL);
//创建3个写线程
for(int i = 0; i < 3; ++i)
{
pthread_create(&pthid[i],NULL,write_func,NULL);
}
//创建5个读线程
for(int i = 3; i < 8; ++i)
{
pthread_create(&pthid[i],NULL,read_func,NULL);
}
//阻塞,资源回收
for(int i = 0; i < 8; ++i)
{
pthread_join(pthid[i],NULL);
}
//释放读写锁资源
pthread_rwlock_destroy(&lock);
return 0;
}
3.2、加读写锁代码执行结果
没有出现,打印的number先大后小的现象。
==write:140429330933504,9235
==write:140429347718912,9236
&&read:140429314148096,9236
&&read:140429305755392,9236
&&read:140429288969984,9236
&&read:140429322540800,9236
&&read:140429297362688,9236
==write:140429339326208,9237
==write:140429330933504,9238
==write:140429347718912,9239