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:

  1. starts produce thread
  2. switches consume thread after signal(mutex)
  3. starts consume thread
  4. switches second consume thread? on wait(taken)
  5. starts second thread
  6. switches third consume thread?? on wait(taken)
  7. segfaults on add2queue

i pretty sure signal() , wait() incorrect , causing problems, can't figure out need change.

please help!


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -