进程同步与互斥

1. 生产者进程和消费者进程对counter的交替操作会使其结果不唯一。

生产者进程和消费者进程的交替执行会导致进程永远等待,造成系统死锁。

2.

semaphore fork[5];

                           for(int i=0; i<5;i++)

                                fork[i]=1;

                      cobegin

                            process philosopher_i( ){

                                       while(ture){

                                                      think( );

                                                       P(fork[i]);

                                                       P(fork[(i+10%5]);

                                                                eat();

                                                       V(fork[i]);

                                                       V(fork[(i+10%5]);

                                                            }

                                           }

coend

3. 

int readcount=0;

semaphore writeblock=1,mutex=1;

cobegin

process reader_i() {

         P(mutex);

       readcount++;

        if(readcount==1)

          P(writerblock);

          V(mutex);

          /*读文件*/

         P(mutex);

         readcount--;

         if(readcount==0)

                  V(writeblock);

           V(mutex);  }

coend

4.

int waiting=0, chairs=n;

semaphore customers=0,barbers=0,mutex=1;

cobegin

     process barbers() {

           while(ture) {

                P(customers);

                P(mutex);

                waiting--;

                V(barbers); 

                V(mutex);

                cuthair();  } }

process customer_i() {

               P(mutex);

               if(waiting<chairs) {

                     waiting++;

                      V(customers);

                       V(mutex);

                       P(barbers):

                       get_haircut();

}

else

        V(mutex);

}

coend

5.

semaphore muext=1;

cobegin

process boss(){

             P(muext);

            /*老板任意出售两种*/

             V(muext);

}

 

process musiclovers_i() {

               while(ture){

                P(muext);

                 listening();

                V(muext);

coend

6.

semaphore mutex=A, customer_count=0:
  main()
  {  
  Cobegin
  Customeri()
  {
  p(mutex);
  取号码,进入队列;
  v(mutex);
  v(customer_count);
  }
  serversi()
  {
  while(A)
  {
  p(customer_count);
  p(mutex);
  从队列中取下一个号码;
  v(mutex);
  为该号码持有者服务;
  }  
  end
  Coend

posted @ 2019-05-06 21:14  吕纯  阅读(109)  评论(0编辑  收藏  举报