首页 > 解决方案 > Functions sem_post, sem_wait and sleep

问题描述

I'm trying to solve the following exercise:

Machine A produces an item every 2 seconds. The AA machine assembles a product from 2 items that machine A had produced.

An AA machine can assemble a product every second, but it needs 2 items per product, so AA is waiting for 2 items from Machine A.

Each machine works in an endless loop, but the factory closes after 20 seconds and does not wait for the machines to finish working.

Write a program that allows the factory and the machines in it, organized work according to the requirements of the factory.

I have the following output, and my code needs to output the same.

Output

I write this:

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <semaphore.h>

sem_t sem1;

void* Machine_A() {
    while(1) {
        printf("Produced A\n");
        sleep(2);   
        sem_post(&sem1);
    }
}

void* Machine_AA() {
    while(1) {
        sem_wait(&sem1);
        sem_wait(&sem1);
        printf("Collected AA\n");
        sleep(1);
    }
}

int main() {
    pthread_t threadA, threadAA;
    sem_init(&sem1, 0, 0);
    pthread_create(&threadA, NULL, Machine_A, NULL);
    pthread_create(&threadAA, NULL, Machine_AA, NULL );
    sleep(20);
    return 0;
}

and I get this output:

3TimesPrinted

I don't understand why machine A prints 3 times at first time and after that it works well.

If I change the code of machine A:

void* Machine_A() {
    while(1) {
        printf("Produced A\n");
        sem_post(&sem1);
        sleep(2);
    }
}

I get the right output.

I don't understand why it prints Produced A 3 times. Every time sem_wait blocks until it becomes possible to perform the decrement.

Thanks!!

标签: cmultithreadingsemaphore

解决方案


推荐阅读