Note that there are some explanatory texts on larger screens.

plurals
  1. POProducer-Consumer with a variation - How to synchronize with thread signal/wait?
    primarykey
    data
    text
    <p>While working on a large project I realized I was making a lot of calls to be scheduled in the future. Since these were fairly light-weight, I thought it might be better to use a separate scheduler.</p> <pre><code>ThreadPool.QueueUserWorkItem (() =&gt; { Thread.Sleep (5000); Foo (); // Call is to be executed after sometime }); </code></pre> <p>So I created a separate scheduler class that runs on its own thread and executes these events. I have 2 functions that access a shared queue from separate threads. I'd use a lock, but since one of the threads needs to sleep-wait, I wasn't sure how to release the lock.</p> <pre><code>class Scheduler { SortedDictionary &lt;DateTime, Action&gt; _queue; EventWaitHandle _sync; // Runs on its own thread void Run () { while (true) { // Calculate time till first event // If queue empty, use pre-defined value TimeSpan timeDiff = _queue.First().Key - DateTime.Now; // Execute action if in the next 100ms if (timeDiff &lt; 100ms) ... // Wait on event handle for time else _sync.WaitOne (timeDiff); } } // Can be called by any thread void ScheduleEvent (Action action, DataTime time) { _queue.Add (time, action); // Signal thread to wake up and check again _sync.Set (); } } </code></pre> <p><li> The trouble is, I'm not sure how to synchronize access to the queue between the 2 functions. I can't use a monitor or mutex, because Run() will sleep-wait, thus causing a deadlock. What is the right synchronization mechanism to use here? (If there a mechanism to atomically start the sleep-wait process and immediately release the lock, that might solve my problem) <li> How can I verify there is no race-condition? <li> Is this a variation of the producer consumer problem, or is there a more relevant synchronization problem-description? <br/><br/> While this is somewhat geared towards C#, I'd be happy to hear a general solution to this. Thanks!</p>
    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