多个线程同时访问共享数据时可能会发生冲突,比如俩个线程都要把某个全局变量加1,这个操作在某平台需要三条指令完成:
1 从内存读变量值到寄存器
2 寄存器的值加1
3 将寄存器的值写到内存
但是俩个线程同在多处理器平台下执行这三条指令,可能会出先变量只加了一次而非俩次,详细说明在APUE第三版 319页
首先读写锁为一把锁,类型为pthread_rwlowk_lock;
类型:读锁为对内存进行读操作,写锁对内存进行写操作
特性:读共享,写独占,读写不能同时,写的优先级要高
比如:线程A加读锁成功,又来三个线程,做读操作,可以加锁成功
线程A加写锁成功,又来三个线程,做读操作,则三个线程阻塞
线程A写锁成功,然后线程B请求读锁,然后线程C请求写锁,应该显示BC阻塞,A解锁后,C加写锁成功,B继续阻塞,C解锁,B加读锁成功
函数:
初始化读写锁:
pthead_rwlock_init(pthread_rwlock_t *restrict rmlock, const pthread_rwlockattr_r *restrict attr); 不写为线程默认属性
销毁读写锁:
pthread_rwclock_destroy(pthread_rwlock_t *rwlock);
加读锁:
pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
尝试加读锁
pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);加锁成功:0 失败:错误号
加写锁:
pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
尝试加写锁:
pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
解锁:
pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
实例:三个线程不定时写同一全局资源,五个线程不定义是读同一全局资源
不加锁:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
int number=0;
void *write_func(void *arg)
{
while(1)
{
number++;
printf("==write: %x,%d\n",(unsigned int)pthread_self(),number);
usleep(500);
}
return NULL;
}
void *read_func(void *arg)
{
while(1)
{
printf("==read:%x,%d\n",(unsigned int)pthread_self(),number);
usleep(500);
}
return NULL;
}
int main()
{
pthread_t p[8];
for(int i=0;i<3;i++)
{
pthread_create(&p[i],NULL,write_func,NULL);
}
for(int i=3;i<8;i++)
{
pthread_create(&p[i],NULL,read_func,NULL);
}
for(int i=0;i<8;i++)
{
pthread_join(p[i],NULL);
}
return 0;
}
运行:
write写完725 才写724出现了数据覆盖
加锁:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
int number=0;
//创建读写锁
pthread_rwlock_t lock;
void *write_func(void *arg)
{
while(1)
{
//加写锁
pthread_rwlock_wrlock(&lock);
number++;
printf("==write: %x,%d\n",(unsigned int)pthread_self(),number);
// 解锁
pthread_rwlock_unlock(&lock);
usleep(500);
}
return NULL;
}
void *read_func(void *arg)
{
while(1)
{
pthread_rwlock_rdlock(&lock);
printf("==read:%x,%d\n",(unsigned int)pthread_self(),number);
pthread_rwlock_unlock(&lock);
usleep(500);
}
return NULL;
}
int main()
{
//init 读写锁
pthread_rwlock_init(&lock,NULL);
pthread_t p[8];
for(int i=0;i<3;i++)
{
pthread_create(&p[i],NULL,write_func,NULL);
}
for(int i=3;i<8;i++)
{
pthread_create(&p[i],NULL,read_func,NULL);
}
for(int i=0;i<8;i++)
{
pthread_join(p[i],NULL);
}
//释放读写锁资源
pthread_rwlock_destroy(&lock);
return 0;
}
不会出现数据读写出错问题