Search code examples
multithreadingproducer-consumer

How to control simultaneous access to multiple shared queues by multiple producers?


One way would be to lock and then check the status of first shared queue, push data if space available, or ignore if not, and then unlock.

Then check the status of second shared queue, push data if space available, or ignore if not, and then unlock.

So, on and so forth.

Here we'll be constantly locking and unlocking to see the status of a shared queue and then act accordingly.


Questions:

What are the drawbacks of this method? Of course time will be spent in locking and unlocking. Is that it?

What are the other ways to achieve the same effect without the current method's drawbacks?


Solution

  • Really, you are making too many locks/unlocks here. The solution is to make the same check twice:

    check if space is available, if not, continue
    lock
    check if space is available AGAIN 
    ... go on as you did before. 
    

    This way you will lock if you needn't to do it only in very rare cases.

    I have first seen the solution in the book "Professional Java EE Design Patterns" (Yener, Theedom)

    Edit.

    About spreading the start queue numbers among threads.

    Notice, that without any special organization these threads are waiting for queues only the first time. The next time the necessary timeshift will be already created by simply waiting. Of course, we can create the timeshift ourselves, spreading the start numbers among threads. And that simple spread by equal shift will be more effective that a random one.