经典进程同步问题(一)——生产者、消费者问题

时间:2022-02-26 16:16:41

今天学习了如题的问题,在此记录。

经典进程同步问题(一)——生产者、消费者问题

下面是每个部分问题的算法实现:

PS:P()、V()操作分别是wait()和signal()原语操作

V1.0

//注意此处的信号量的初始值
Semaphore full = 0;
//下边的两个进程执行顺序没有先后
Produce:
    ...;
    put product to buffer;
    V(full);
    ...;

Consumer:
    ...;
    P(full);
    take product from buffer;
    ...;

V2.0

Semaphore empty = 0,full = 0;

Producter:
    while(true){
    ...;
    P(empty);
    put product into buffer;
    V(full);
    ...;
    }

Consumer:
    while(true){
    ...;
    P(full);
    get product from buffer;
    V(empty);
    ...;
    }

V3.0

Semaphore empty = 0,full = 0;

Producter:
    while(true){
    ...;
    P(empty);
    put product into buffer;
    V(full);
    ...;
    }

Consumer:
    while(true){
    ...;
    P(full);
    get product from buffer;
    V(empty);
    ...;
    }

V4.0

//信号量
Semaphore empty = 0,full = 0,mutex = 1;

//公共变量
item buffer[n];
int i = 0,j = 0;

Producter:
    while(true){
    ...;
    P(empty);//限制一次进入一个进程
    P(mutex);//限制一次只能进入一个缓冲区
    buffer[i] = product;
    i = (i + 1) mod n;
    V(mutex);
    V(full);
    ...;
    }

Consumer:
    while(true){
    ...;
    P(full);
    P(mutex);
    take buffer[j];
    j = (j + 1) mod n;
    V(mutex);
    V(empty);
    ...;
    }