Home > Software design >  Producer Consumer should I use a mutex or a semaphore
Producer Consumer should I use a mutex or a semaphore

Time:05-04

I have 2 threads, the producer thread receives some data over an internet socket, constructs an object and adds it to a queue and the consumer thread pops items from that same queue and does some processing.

Since both threads modify the queue (by enqueuing and dequeuing respectively) I think using a mutex in both threads should be sufficient. Is this a good approach or should I use a semaphore? If so, why?

CodePudding user response:

Either can be made to work. It depends on details of the actual design. How many producer/consumer requests will you allow simultaneously? Is it truly limited to two threads, or will the code spawn others as more requests occur?

I found this short blog interesting. It discusses and compares both the Mutex and Semaphore and may give you some ideas.

"A mutex object allows multiple process threads to access a single shared resource but only one at a time. On the other hand, semaphore allows multiple process threads to access the finite instance of the resource until available. In mutex, the lock can be acquired and released by the same process at a time."

Examples in C

  • Related