Skip to content
Advertisement

Multithreading with Semaphor, Mutex and PThread

Me and a friend are currently working on basic multithreading examples for university in c. We’re supposed to solve the producer/consumer problem with a multithreaded buffer. We’ve got a working version using mutex and conditional variables, but trying to solve this using semaphores and mutex were having three major problems.

Problem 1: If we start the consumer first he sometimes randomly consumes an invalid char and crashes.

Problem 2: If we start the producer first, he sometimes doesnt produce any chars until the consumer is started, which leads to problem 1.

Problem 3: Our producers dont fill the whole buffer, after every insertion in the buffer the consumer is consuming, no matter how many producers there are.

According to our given pseudocode-examples atleast problem 2&3 shouldnt be existing. Im really grateful for any answers, since Im not able to find the mistake at the moment.

Consumer:

JavaScript

Producer:

JavaScript

main:

JavaScript

Advertisement

Answer

Function sem_open creates global (named) semaphore, which exists until sem_unlink() is called.

When you run your program second time (and further), sem_open reuses already existed semaphore, and its value isn’t reseted. You can easily detect that:

JavaScript

Actually, when a semaphore is used only by single process (but many threads), it is sufficient to initialize it with sem_init:

JavaScript

Alternatively, you may destroy old semaphore before attempt to create new one:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement