}
pthread_mutex_unlock(&readerLock);//释放时,写者将优先获得readerLock }
pthread_mutex_unlock(&outerLock);
read();
pthread_mutex_lock(&accessReaderCnt);//代码段2 {//临界区
readerCnt--;
if(readerCnt == 0){
pthread_mutex_unlock(&writeLock);//在最后一个并发读者读完这里开始禁止写者执行写操作 } }
pthread_mutex_unlock(&accessReaderCnt);
sleep(R_SLEEP); }
pthread_exit((void *) 0); }
int main() {
int i = 0;
for(i = 0; i < N_READER; i++) {
pthread_create(&rid[i],NULL,reader,NULL); }
for(i = 0; i < N_WRITER; i++) {
pthread_create(&wid[i],NULL,writer,NULL); }
while(1){
sleep(10); }
return 0; }
【实验结果】
5
结果截图如下:
实验结果分析:写者优先于读者
3. 编写一个使用线程并共享一个公共缓冲区的生产者-消费者问题。但是,不要使用信号量或任何其他用来保护共享数据结构的同步原语。直接让每个线程在需要访问时就访问。使用sleep和wakeup来处理满和空的条件。观察需要多长时间会出现比较严重的竞争条件。例如,可以让生产者一会儿打印一个数字,每分钟打印不要超过一个数字,因为I/O会影响竞争条件。(课本98页作业题53)
代码:
#include
#define N 5 //缓冲区中的槽数目
pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int count = 0;
6
void *producer(void *ptr) { int i;
for(i=1; i<= MAX; i++) { if(count==N) pthread_cond_wait(&condp,&the_mutex); count=count+1; sleep(1); if(i`==0) printf(\ if(count==1) pthread_cond_signal(&condc); }
return ((void *)0); }
void *consumer(void *ptr) { int i;
for(i=1; i <= MAX; i++) { if(count==0) pthread_cond_wait(&condc,&the_mutex); count=count-1; sleep(2); if(count==N-1) pthread_cond_signal(&condp); }
return ((void *)0); }
int main() {
pthread_t pro,con;
pthread_mutex_init(&the_mutex,0); pthread_cond_init(&condc,0); pthread_cond_init(&condp,0);
pthread_create(&con,NULL,consumer,NULL); pthread_create(&pro,NULL,producer,NULL); pthread_exit((void *)pthread_self());
7
return 0; }
【实验结果】
【实验总结】
实验过程中遇到的问题及解决方法,心得,建议,意见
问题:伪代码大概知道怎么写,但是要写可运行程序的时候觉得一头雾水,不懂 解决方法:摆渡之,google之,最后对照着代码分析理解感悟,最后感觉有点懂了
心得建议体会:
这次实验让我加深了对进程和线程的理解,进程具有相对的独立性,系统调用可以方便用户和系统对进程进行控制,以确保资源的有效率分配。线程作为轻量级的进程,极大地帮助了进程的工作。对于系统的资源分配,生产者-消费者问题提供了通过控制信号量和互斥量的方法来控制资源的有效访问。 建议:实验有一定的难度,希望能讲解多一点。
8
百度搜索“70edu”或“70教育网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,70教育网,提供经典综合文库操作系统—进程管理(2)在线全文阅读。
相关推荐: