#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int counter;
pthread_rwlock_t rwlock;
void *th_write(void *arg);
void *th_read(void *arg);
int main(int argc, char *argv[])
{
int i = 0;
pthread_t tid[8];
pthread_rwlock_init(&rwlock, NULL);
//创建三个写线程
for(i = 0; i<3; i++)
{
pthread_create(&tid[i], NULL, th_write, (void*)i);//不能&i 和 i = *((int*)arg)
}
//创建5个读线程
for(i = 0; i<5; i++)
{
pthread_create(&tid[i+3], NULL, th_read, (void*)i);
}
for(i = 0; i < 8; i++)
{
pthread_join(tid[i], NULL);
}
pthread_rwlock_destroy(&rwlock);
}
void *th_write(void *arg)
{
int i = (int)arg;
int t = 0;
for( ; ; )
{
pthread_rwlock_wrlock(&rwlock);
t = counter;
usleep(1000);
printf("write %d: %lu: counter = %d ++counter = %d\n", i, pthread_self(), t, ++counter);
pthread_rwlock_unlock(&rwlock);
usleep(10000);//这个延时大的目的是让读锁有机会进行读,不然一直让写锁独占
}
return NULL;
}
void *th_read(void *arg)
{
int i = (int)arg;
for( ; ; )
{
pthread_rwlock_rdlock(&rwlock);
printf("read %d: %lu: counter = %d\n", i ,pthread_self(), counter);
pthread_rwlock_unlock(&rwlock);
usleep(2000);
}
return NULL;
}