c - I can't figure out what is wrong with my semaphore implementation -
i need implement producers , consumers in c89 using semaphores.
i admit school assignment, going use pseudocode.
it took me forever simplify code, can figure out wrong
there 1 global variable:
threadqueue ready; //global queue holds threads ready run
these functions use in code. tried make them self-explanatory:
newthread(function); //turns function thread rotatequeue(queue); //rotates queue head becomes tail , next becomes head add2queue(thread, queue); //adds thread queue runthread(newthread); //stops current thread, , runs newthread removehead(queue); //removes head of queue , returns
here how designed semaphore:
struct semaphore{ threadqueue queue; int val; } wait(semaphore s) { if(--s.val < 0) { add2queue(currentthread, s.queue); runthread(ready.head); } } signal(semaphore s) { if(s.val++ < 0) { add2queue(removehead(s.queue), ready); } rotatequeue(ready); runthread(ready.head); }
finally run code:
semaphore mutex = 1; semaphore taken = 0; semaphore remaining = number; producer() { while(1) { wait(remaining); wait(mutex); //critical section signal(mutex); signal(taken); } } consumer() { while(1) { wait(taken); wait(mutex); //critical section signal(mutex); signal(remaining); } } main() { thread produce = newthread(producer); thread consume = newthread(consumer); add2queue(produce, ready); add2queue(consume, ready); runthread(ready.head); }
my code this:
- starts produce thread
- switches consume thread after signal(mutex)
- starts consume thread
- switches second consume thread? on wait(taken)
- starts second thread
- switches third consume thread?? on wait(taken)
- segfaults on add2queue
i pretty sure signal() , wait() incorrect , causing problems, can't figure out need change.
please help!