操作系统—读者写者问题
2013-05-21 21:57
232 查看
/* * 读者写者问题,读者写者是否公平竞争,读优先写优先不同 * 读者之间不互斥,可以多个读操作同时进行 * 读操作和写操作不可以同时进行(R-W,互斥) * 写操作和写操作不可以同时进行(W-W,互斥) * 在实际应用中,写优先非常重要,因为写代表的是对数据的更新。 * 而我们希望读到的是最新的消息。因此继续进行改进,就要考虑, * 如果写者到来,可以让正在读的读者让路,先让写者写。 * 要求实现的是读者写者公平 */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #define N 20 int readcount=0,writecount=0; sem_t s,w;// 同步信号量 pthread_mutex_t mutex,wmutex; void *writer(void *a)//读者写者公平 { while(1) { sleep(1); pthread_mutex_lock(&wmutex);//P(wmutex); writecount++; if(writecount==1) sem_wait(&s);//P(S); pthread_mutex_unlock(&wmutex);//V(wmutex); sem_wait(&w);//P(w); printf("Writing is writing\n");//写 sleep(1); sem_post(&w);//V(w); pthread_mutex_lock(&wmutex);//P(wmutex); writecount--; if(writecount==0) sem_post(&s);//V(S); pthread_mutex_unlock(&wmutex);//V(wmutex); } } void *reader(void *a)//读者写者公平 { while(1) { sleep(1); sem_wait(&s);//P(S); pthread_mutex_lock(&mutex); //给互斥体变量加锁//P(mutex); readcount ++; if(readcount==1) sem_wait(&w);//P (w); pthread_mutex_unlock(&mutex);//V(mutex); sem_post(&s); //V(S); printf("Reader is reading\n");//读 sleep(1); pthread_mutex_lock(&mutex); //P(mutex); readcount --; if(readcount==0) sem_post(&w);//V(w); pthread_mutex_unlock(&mutex);//V(mutex); } } int main() { int i; int ret ; // 初始化同步信号量 int ini1 = sem_init(&s, 0, 1);//函数sem_init()用来初始化一个信号量 int ini2 = sem_init(&w, 0, 1); if(ini1!=0 ||ini2 != 0) { printf("sem init failed \n"); exit(1); } //初始化互斥信号量 int ini3 = pthread_mutex_init(&mutex, NULL); int ini4 = pthread_mutex_init(&wmutex, NULL); if(ini3 !=0 ||ini4!=0) { printf("mutex init failed \n"); exit(1); } pthread_t id1 ; pthread_t id2 ; for(i = 0; i < 10; i++) { pthread_create(&id2[i], NULL, reader, NULL); } for(i = 0; i < 5; i++) { ret[i] = pthread_create(&id1[i], NULL, writer, (void *)(&i)); if(ret[i] != 0) { printf("product%d creation failed \n", i); exit(1); } } for(i = 10; i < 20; i++) { ret[i] = pthread_create(&id2[i], NULL, reader, NULL); if(ret[i] != 0) { printf("prochase%d creation failed \n", i); exit(1); } } for(i = 5; i < 10; i++) { ret[i] = pthread_create(&id1[i], NULL, writer, (void *)(&i)); if(ret[i] != 0) { printf("product%d creation failed \n", i); exit(1); } } for(i = 0; i < N; i++)//销毁线程 { pthread_join(id1[i],NULL); pthread_join(id2[i],NULL); } exit(0);//还是完全没搞清楚多线程怎么在运行,郁闷 //执行结果有问题,不过助教还是让过了,并讲解一番,赞一个 :) }
相关文章推荐
- 优先读者/写者问题—操作系统
- Windows操作系统实习之读者-写者问题
- 操作系统 读者写者问题(含有swing)
- 现代操作系统-读者/写者问题
- 【经典操作系统问题】读者写者问题分析
- 操作系统进程同步互斥经典问题之读者写者问题
- 操作系统算法:如何利用信号量实现优先级(从读者写者问题引发的联想)
- 操作系统——读者写者问题(读者优先、强写者优先 和 公平竞争)
- 操作系统——读者写者问题详解
- 操作系统进程同步三大问题:生产者消费者,哲学家进餐,读者写者问题
- 操作系统实验,IPC(2): reader and writer, 读者和写者问题
- 操作系统同步互斥经典问题——读者写者问题
- 操作系统清华大学版笔记(十) 信号量、管程、条件互斥、经典同步问题(读者写者、哲学家问题)
- 操作系统中读者-写者问题的一点疑问
- 操作系统之读者与写者问题
- 操作系统PV操作及读者写者问题
- 操作系统同步互斥经典问题——读者写者问题
- 经典同步互斥问题之读者—写者问题
- Linux多线程──读者写者问题
- 进程同步的经典问题1——读者写者问题(写者优先与公平竞争)