• Post Reply Bookmark Topic Watch Topic
  • New Topic

regarding producer/consumer example

 
Richard Agnes
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a fairly newbie question, but with reference to the producer consumer examples given in most tutorials on Threads, I understand the concept of synchronizing for getting and setting the data, but what if I want to control access for 2 consumers instead of just one, how would I code this, i.e what if I want to producer to say set the message, but I want 2 consumers to retrieve the message before a new message can be set. What about n consumers where n is determined at run time?
is the question clear or should I give code example?
thanks.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two ingredients, I think:-- notifyAll and a subscription mechanism.
The notifyAll method will wake up all your waiting threads, so all your consumers get an opportunity to pick up your message.
The subscription mechanism should be able to tell the producer when a new message can be added. A simple counter probably won't cut it, unless it is OK that a new message can be posted only if all consumers are wait()ing for it.
When a consumer subscribe()s, you can add it to a Collection ("subscribers") -- using something which uniquely identifies the consumer, probably its Thread.currentThread(). When posting a new message, you shallow-copy the Collection to a second Collection ("recipients") and notifyAll().
Each time a consumer wants to retrieve a message, you check it against "recipients"; if it's in there, you remove the consumer from "recipients" and return the message. Otherwise the consumer must wait().
Only when "recipients" is empty you can post a new message and notifyAll() the consumers waiting for the next message.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!