circular buffer problem

Topic: A ring buffer is composed of 6 buffers 0~5, where Full means a buffer full of data, and Empty means an empty buffer. Clockwise, the pointer Pf points to the first "full" buffer, and the pointer Pe points to the first "empty" buffer. The process In continuously inputs data into Empty under the instruction of Pe, and the process Out continuously takes out data from Full under the instruction of Pf. When all buffers are "full" buffers, Pe points to "null". When all buffers are "null" buffers, Pf points to "null". In the initial state, all buffers are "empty" buffers, and Pe points to No. 0 buffer. Use semaphore and P, V primitives to write out the synchronization algorithm of process In and Out.

Define the semaphore

mutex = 1, empty = 6, full = 0;

In process

void in() {
    wait(empty);
    wait(mutex);
    if (Pf == NULL) Pf = Pe;
    // 向Pe指向的缓冲区写入数据
    Pe = (Pe + 1) % 6;
    if (Pe == Pf) Pf = NULL;
    signal(mutex);
    signal(full);
}

Out process

void out() {
    wait(full);
    wait(mutex);
    if (Pe == NULL) Pe = Pf;
    // 从Pf指向的缓冲区取出数据
    Pf = (Pf + 1) % 6;
    if (Pf == Pe) Pe = NULL;
    signal(mutex);
    signal(empty);
}

Guess you like

Origin blog.csdn.net/m0_64140451/article/details/131263943