Note that there are some explanatory texts on larger screens.

plurals
  1. POthread-safe inside thread worker
    text
    copied!<p>I am wondering how to do inside executional thread to be thread safe, let me explain it by example:</p> <p>lets say that I want to have pipeline of commands which should be executed continuously one by one, but in my thread I can't wait for them. Thread is normally slept, is awaeken if some command is enqueued, then it executes all commands in the queue and again goes to sleeping mode until new command is being enqueued. something like: </p> <pre><code> public void Enqueue(ICommand command) { this.queue.Enqueue(command); this.synchroHandler.Set(); } private void Pipeline() { while (true) { this.synchroHandler.WaitOne(); while (this.queue.Count > 0) { ICommand command = this.queue.Dequeue(); command.Execute(); } // what if command will be enqueued between previous command - HERE // ... and this command HERE this.synchroHandler.Reset(); } } public void Main() { this.queue = new ThreadSafeQueue&lt;ICommand&gt;(); this.computionHandler = new ManualResetEvent(false); Thread thread = new Thread(new ThreadStart(this.Pipeline)); thread.Start(); // start adding commands to pipeline this.Enqueue(command1); this.Enqueue(command2); ... } </code></pre> <p>lets say my implementation of queue is thread-safe so this.queue.Count, this.queue.Enqueue and this.queue.Dequeue use same lock. Ss shown in the example if public Enqueue() will be invoked between the "}" and this.synchroHandler.Reset(); thread will ends up slept even if it has one item in the queue (this.synchroHandler.Set() will be invoked right before this.synchroHandler.Reset()). Any idea how to make this schema thread-safe?</p>
 

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