d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Some Help With Semaphores
Add Reply New Topic New Poll
Member
Posts: 29,197
Joined: Feb 5 2007
Gold: 4,000.18
Feb 24 2013 09:26am
There is a main class starting threads for Producers and Consumers in this manner (Producers push onto a stack, consumers pop):

Consumer.start()
Producer.start()
Consumer.start()
Producer.start()


I need to make sure that the 2 producers enter first, then the 2 consumers.


Right now I have a semaphore.wait() (set to 0 initially so it won't run) in the Consumer class. Right now I'm using semaphore.signal() at the end of the Producer class, but that isn't right (I need the 2 Producers to run first).

Where can I put my semaphore.signal() ? (I can't change my main, so I can't put it after my second Producer.start() :( )


/e It seems as if my code is running correctly, but I'm pretty sure it's just a coincidence xD

This post was edited by IsraeliSoldier on Feb 24 2013 09:28am
Member
Posts: 2,579
Joined: Jun 1 2012
Gold: 1,524.00
Feb 24 2013 04:11pm
Kind of hard to understand your question, but if you need both Producers to run before either of the Consumers run, you could initialize the semaphore to -1, then have each Consumer wait on the semaphore while each Producer runs and then signals the semaphore when done.

Ex:

Semaphore S = -1

Consumer
Code

S.wait();
// Consume Stuff
S.signal();


Producer
Code

// Produce Stuff
S.signal();


This post was edited by Schwag on Feb 24 2013 04:18pm
Member
Posts: 2,579
Joined: Jun 1 2012
Gold: 1,524.00
Feb 24 2013 04:55pm
Oops, I meant initialize it to 1, not -1; can't edit again though.
Member
Posts: 29,197
Joined: Feb 5 2007
Gold: 4,000.18
Feb 26 2013 09:57pm
Quote (Schwag @ Feb 24 2013 05:55pm)
Oops, I meant initialize it to 1, not -1; can't edit again though.


I got it to work, I actually needed 3 Semaphores ><. There were 4 threads created, so:

1 semaphore to make sure only 1 Producer is allowed in at a time to keep mutual exclusion
1 semaphore used as a mutex for Producer and Consumer
1 semaphore used to signal the Consumer when all producers are done

Thanks for the help :)

This post was edited by IsraeliSoldier on Feb 26 2013 09:57pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll