-
#include <stdio.h>
-
#include <unistd.h>
-
#include <pthread.h>
-
#include<stdlib.h>
-
-
int a = 200;
-
int b = 100;
-
pthread_rwlock_t lock;
-
-
void* ThreadA(void*argc)
-
{
-
printf("pthreadA is running\n");
-
pthread_rwlock_wrlock(&lock); //写锁
-
printf("pthreadA write locked...\n");
-
a -= 50;
-
sleep(5); //执行到一半 使用sleep 放弃cpu调度
-
b += 50;
-
pthread_rwlock_unlock(&lock);
-
printf("pthreadA write unlocked...\n");
-
printf("pthreadA exit\n");
-
}
-
-
void* ThreadB(void*argc)
-
{
-
sleep(1); //放弃CPU调度
-
printf("pthreadB is running\n");
-
pthread_rwlock_rdlock(&lock);
-
printf("pthreadB read locked...\n");
-
printf("%d\n", a + b);
-
sleep(2);//让线程C读
-
pthread_rwlock_unlock(&lock);
-
printf("pthreadB read unlocked...\n");
-
printf("pthreadB exit\n");
-
}
-
-
void* ThreadC(void*argc)
-
{
-
sleep(1); //放弃CPU调度
-
printf("pthreadC is running\n");
-
pthread_rwlock_rdlock(&lock);
-
printf("pthreadC read locked...\n");
-
printf("%d\n", a + b);
-
pthread_rwlock_unlock(&lock);
-
printf("pthreadC read unlocked...\n");
-
printf("pthreadC exit\n");
-
}
-
-
int main()
-
{
-
pthread_t tida, tidb,tidc;
-
pthread_rwlock_init(&lock, NULL);
-
pthread_create(&tida, NULL, ThreadA, NULL);
-
pthread_create(&tidb, NULL, ThreadB, NULL);
-
pthread_create(&tidc, NULL, ThreadC, NULL);
-
pthread_join(tida, NULL);
-
pthread_join(tidb, NULL);
-
pthread_join(tidc, NULL);
-
pthread_rwlock_destroy(&lock);
-
exit(0);
-
}
运行结果如下:
pthreadA is running
pthreadA write locked...
pthreadB is running
pthreadC is running
pthreadA write unlocked...
pthreadA exit
pthreadB read locked...
300
pthreadC read locked...
300
pthreadC read unlocked...
pthreadC exit
pthreadB read unlocked...
pthreadB exit
将代码的第30行注释掉,运行结果如下:
pthreadA is running
pthreadA write locked...
pthreadB is running
pthreadC is running
pthreadA write unlocked...
pthreadA exit
pthreadB read locked...
300
pthreadB read unlocked...
pthreadB exit
pthreadC read locked...
300
pthreadC read unlocked...
pthreadC exit
本文未详细说明,看不懂可以通过左上角联系方式联系我
阅读(1428) | 评论(0) | 转发(0) |