0

I'm new to linux thread semaphore.

There is no error, no warning, and result output.

What cause this happen?

I suspect semaphore is blocked or infinite loop.

Anyone can see logic incorrect in some place?

initialise sem vlaue : bin_sem = 0, pile_sem = 0, fuel_sem = 0

sem_t bin_sem, pile_sem, fuel_sem;

int pile=0, fuel=0, wantedMineralVal=3, foundMineral=-1;


int isFound(void){
    srand(time(NULL));
    return (rand()%8+1);
}

void checkResource(){
    if(fuel!=0 && pile!=0)
        sem_post(&bin_sem); 
}

void *deliverFuel(void *args){
    while(foundMineral!=wantedMineralVal){      
        sem_wait(&fuel_sem);
        fuel+=24;
        checkResource();
    }
}

void *deliverPile(void *args){
    while(foundMineral!=wantedMineralVal){
        sem_wait(&pile_sem);
        pile+=12;
        checkResource();
    }
}

void *drilling(void *args){
    do{ 
        foundMineral =  isFound();
        if(pile == 0 || fuel==0){
            sem_post(&pile_sem);
            sem_post(&fuel_sem);
            sem_wait(&bin_sem);
        }

    pile-=2;
    fuel-=4;

    }while(foundMineral!=wantedMineralVal);

}
Txuver Jhi Wei
  • 318
  • 2
  • 5
  • 17
  • How many threads are running? Which thread calls which function? If it's only one thread, then when it goes to sleep on a semaphore then there won't be anyone else to wake it up. – Shloim Sep 11 '16 at 08:16
  • pthread_create(&worker_thread, NULL, drilling, NULL); pthread_create(&fuelSp_thread, NULL, deliverPile, NULL); pthread_create(&pileSp_thread, NULL, deliverFuel); 3 threads is created – Txuver Jhi Wei Sep 11 '16 at 08:31
  • A couple of problems which may or may not be the cause of the problem: 1. Linux concurrency primitives can never be expected to print any errors or warnings. There are no illegal operations on semaphores that I know of. 2. You do srand(time(NULL)) before every rand() call which is wrong and will cause rand() to return the same value every time it's called during a second. Call srand() only once. 3. bin_sem is posted twice but only waited once so it seems like it will just continue counting upwards? Is this intended? – jforberg Sep 11 '16 at 10:06
  • 4. rand() and srand() are not thread safe, while your usage as seen in only this code sample **would** work, in general (and especially in a homework context) it's not correct to do it that way. Likely symptoms include rand() returning the same value twice in different threads. Always use rand_r() in concurrent programs, and prefer it in most other situations. – jforberg Sep 11 '16 at 10:17
  • the posted code does not compile. Suggest starting with inserting the `#include` needed statements. – user3629249 Sep 12 '16 at 16:16

0 Answers0