日期:2014-05-16  浏览次数:20754 次

linux进程协作-一个小例子

       爸爸给女儿和儿子喂水果。爸爸随机挑选橘子或者苹果,将橘子剥皮或者将苹果削皮放在盘子中,剥皮的速度比较快,而削皮的时间比较慢。女儿只吃橘子,儿子只吃苹果(当然我们假设女儿和儿子永远也吃不饱)。盘子只能装下3个水果。儿子吃得比较快,女儿吃得比较慢。

编程模拟该过程:

简单分析

信号量:

int accessplate = 1;     //表示访问盘子的信号量

int apple = 0;                    //苹果个数

int orange = 0;                  //橘子

int emptyplates = 3;          //空盘子

Father:

P(emptyplates);

produce a fruit

if( is apple )

then

         P(accessplate)

         put  apple in

         V(apple)

         V(accessplate)

else

         P(accessplate)

         put  orange in

         V(orange)

         V(accessplate)

Boy:

P(apple)

P(accessplate)

get an apple

eat an apple

V(emptyplates)

V(accessplate)

 

Girl:

P(orange)

P(accessplate)

get an orange

eat an orange

V(emptyplates)

V(accessplate)

 

代码:

#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/sem.h>
 
/*overall varible*/
int numOfEmptyPlate_sem_id = 0; //number of empty plates.
int numOfApple_sem_id = 0; //number of apple
int numOfOrange_sem_id = 0; //number of orange
int getAccesstoPlate = 0; //get plate
int *plate = NULL;         //3 PLATES
struct sembuf P, V;    // p,v opration
 
void printPlates(const char *arg)
{
    int i = 0;
    printf("%s\nFruits in plates:", arg);
    for(i=0; i<3; i++)
    {
        printf("%d ", plate[i]);
    }
    printf("\n");
}
 
void father_do()  // PUT FRUITS in
 
{// 1 == apple, 2 ==  range
    int i = 0;
    semop( numOfEmptyPlate_sem_id, &P, 1); // P(empty plates)
    if( rand()%100+1 > 50)  //get an orange
    {
        sleep(1);  //get an orange,sleep 1 seconds
        semop( getAccesstoPlate, &P, 1); //P(plate)
        printf("Father get access to the plates.\n");
        printPlates("father:");
        for(i=0; i<3; i++)
        {
            if( 0 == plate[i])  //find an empty plate, and put the furit in
            {
                printf("%d ", plate[i]);
                plate[i] = 2;
                break;
            }
        }
        semop( numOfOrange_sem_id, &V, 1); //V(oranges)
        printf("Father put an orange in plate.\n");
        semop( getAccesstoPlate, &V, 1); //V(plate)
        printf("Father put the plates back.\n");
    }
    else   // get an apple
    {
        sleep(2); //get an apple,sleep 2 seconds
        semop( getAccesstoPlate, &P, 1); //P(plate)
        printf("Father get access to the plates.\n");
        printPlates("father:");
        for(i=0; i<3; i++)
        {
            if( 0 == plate[i])  //find an empty plate, and put the furit in