1
votes

I have created a program in C that creates 2 buffers. The buffer indices hold single characters, 'A' or 'b' etc... In order to learn more about multithreading, I created a set of semaphores based on the producer/consumer problem to produce characters and consume characters from the buffers. I have 3 producer threads for each buffer and 10 consumer threads. The consumers take one item from each buffer, then report it (freeing the memory of the consumed item also). Now, from what I've read, sem_wait() is supposed to signal the "longest waiting thread" when it comes out of a blocking state (I read this in a book and in an online POSIX library).

Now, is this actually true?

The application I have made should have both consumers and producers waiting at the same sem_wait() gate, but the producers get into the critical section more than double the time of any consumer. The consumers do have an extra semaphore to wait for, but that shouldn't make that huge of a difference. I can't seem to figure out why it's happening, so I'm hoping someone else does. If I sleep(1) on the producer threads, the consumers get in just fine and the buffers hover around 0 items...like I would think would happen otherwise.

Also, should thread creation order play any role in how I structure the program for fairness?

IE, produce one of each type in a round robin fashion until everyone is created and running.

Are there any methods anyone can describe to me to institute a more fair system of thread access? I've read that creating a FIFO queue system might be one solution, where the longest waiting thread has the highest priority (which is what I thought sem_wait() would do anyways).

Just wondering what methods are out there for both rudimentary and higher level threading.

2

2 Answers

4
votes

The POSIX standard actually says that "the highest priority thread that has been waiting the longest shall be unblocked" only when the SCHED_FIFO or SCHED_RR scheduling policy applies to the blocked thread.

If you're not using one of those two realtime scheduling policies, then the semaphore does not have to be "fair".

-1
votes

Multi-threaded software only makes sense when

  1. You have multiple core to play with
  2. Some algorithms are easier to program

How do you define fair. Surely it is better if a core has nothing to do then they take on the work. Does it matter if one core never gets a lookin?