Note that there are some explanatory texts on larger screens.

plurals
  1. POMultithreading Multiple Producer and Consumer Threads Won't Sync BlockingCollection Race Condition
    primarykey
    data
    text
    <p>I have multiple producers and multiple consumers. My shared resource is the BlockingCollection. However, my code only works if I have one consumer. I know it is a race condition since the output is different each time I run the code. </p> <p>I thought BlockingCollection would take care of all the syncing etc. but it does not.</p> <p>How can I sync my shared resource among all the producers and consumers then?</p> <p>Here is my code:</p> <pre><code>/// &lt;summary&gt; /// PURE PRODUCER TYPE /// &lt;/summary&gt; class Caller { private BlockingCollection&lt;Call&gt; incommingCalls; public Caller(BlockingCollection&lt;Call&gt; calls) { incommingCalls = calls; //start the producer thread Thread thread = new Thread(new ThreadStart(placeCall)); thread.Start(); } public void placeCall() { incommingCalls.Add(myCall); } } /// &lt;summary&gt; /// CONSUMER /// &lt;/summary&gt; class Fresher : Employee { private BlockingCollection&lt;Call&gt; calls; public Fresher(BlockingCollection&lt;Call&gt; incalls) { calls = incalls; Thread thread = new Thread(new ThreadStart(HandleCalls)); thread.Start(); } /// &lt;summary&gt; /// /// &lt;/summary&gt; public void HandleCalls() { while (!incommingCalls.IsCompleted) { Call item; if (incommingCalls.TryTake(out item, 100000)) { //do something with the call } //else do nothing - just wait } } /// &lt;summary&gt; /// /// &lt;/summary&gt; class CallCenter { private BlockingCollection&lt;Call&gt; fresherCalls; private List&lt;Caller&gt; myCallers; private List&lt;Employee&gt; myFreshers; public CallCenter() { //initial incomming calls to the fresher queue fresherCalls = new BlockingCollection&lt;Call&gt;(); myFreshers = new List&lt;Employee&gt;(); myCallers = new List&lt;Caller&gt;(); generate_freshers(); //generate to start the producer generate_callers(); } /// &lt;summary&gt; /// /// &lt;/summary&gt; private void generate_freshers() { for (int i = 0; i &lt; 1; i++ ) { myFreshers.Add(new Fresher(fresherCalls, tlCalls, locker2)); } } /// &lt;summary&gt; /// /// &lt;/summary&gt; private void generate_callers() { for (int i = 0; i &lt; 20; i++ ) { myCallers.Add(new Caller(fresherCalls, locker)); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload