vendredi 8 novembre 2019

Using semaphores in c++ for synchronization

I am trying to use sem_init, sem_wait, and sem_post for process syncronization. My algorithm should have 2 producers and 2 consumers still in a single queue.

My program has to create 4 threads and two producer processes should fill the buffer with some value (start at 1000 for one of the producers and 2000 for the other and increment each time).

Two consumer processes that continuously consume items from the buffer.

Have each of the producer(s) and consumer(s), produce one line of output each cycle identifying itself, and printing the value of the 2 pointers.

After the 4 threads terminate, have the main program output the entire buffer before terminating.

I have created a method called task to sem_wait and sem_post and created four threads. However I am not sure of how to fill the buffer and get values from the buffer using produces and consumer processes. and describing the processes.

Here is my code so far.

#include <iostream>  
#include <semaphore.h>
#include <thread>
#include <chrono>
#include <mutex>
#include <string>
#include <unistd.h> 
#include <stdio.h> 

sem_t mutex;
sem_t full;
sem_t empty;

void* task(void* arg)
{
    sem_wait(&mutex);
    sem_wait(&full);
    sem_wait(&empty);

    sleep(4);

    sem_post(&mutex);
    sem_post(&full);
    sem_post(&empty);

}

int main() 
{
    sem_init(&mutex, 0, 1);
    sem_init(&full, 0, 0);
    sem_init(&empty, 0, 1);

    std::thread t1(task, "Thread 1");
    std::thread t2(task, "Thread 2");
    std::thread t3(task, "Thread 1");
    std::thread t4(task, "Thread 2");
    t1.join();
    t2.join();   
    t3.join();
    t4.join();
}

and here I have the structure of consumer and producer processes

//structure of consumer process
    while (true) {
        sem_wait(full);
        sem_wait(mutex);

        /* remove an item from buffer to next_consumed */
        signal(mutex);
        signal(empty);
        /* consume the item in next consumed */
    };

    //structure of producer process
    while (true) {
    /* produce an item in next_produced */

    wait(empty);
    wait(mutex);

    /* add next produced to the buffer */
    signal(mutex);
    signal(full);
    };

Please let me know what steps I should take to accomplish this.

Aucun commentaire:

Enregistrer un commentaire