读写锁的适用场景:大量读操作,少量写操作;
读并行,读写互斥,写互斥;
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
pthread_rwlock_t rwlock;
int num=0;
void* write_func(void* arg)
{
while(num<20000)
{
pthread_rwlock_wrlock(&rwlock);
printf("write:%lu %d\n",pthread_self(),num++);
pthread_rwlock_unlock(&rwlock);
usleep(500);
}
pthread_exit(NULL);
}
void* read_func(void* arg)
{
while(num<20000)
{
pthread_rwlock_rdlock(&rwlock);
printf("read:%lu %d\n",pthread_self(),num);
pthread_rwlock_unlock(&rwlock);
usleep(500);
}
pthread_exit(NULL);
}
int main()
{
int i=0;
pthread_t pthread_id[8]={0};
/*线程分离*/
/* pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);*/
/*初始化读写锁*/
pthread_rwlock_init(&rwlock,NULL);
/*创建三个写线程*/
for(;i<3;i++)
{
strerror(pthread_create(&pthread_id[i],NULL,write_func,NULL));
}
/*创建五个读线程*/
for(i=3;i<8;i++)
{
strerror(pthread_create(&pthread_id[i],NULL,read_func,NULL));
}
/*销毁线程分离属性*/
//pthread_attr_destroy(&attr);
/*销毁读写锁*/
for(i=0;i<8;i++)
{
pthread_join(pthread_id[i],NULL);
printf("thread %d has finished!\n",i);
}
pthread_rwlock_destroy(&rwlock);
return 0;
}
注意:在销毁读写锁或者互斥锁之前一定要保证所有子线程已经退出。在子线程还没退出前销毁读写锁或者互斥锁会导致子线程终止;
还有,设置线程分离之后不能再用pthread_join()回收子线程,否则会造成程序崩溃;