c# - Synchronization accross threads / atomic checks? -
c# - Synchronization accross threads / atomic checks? -
i need create method invoker thread (thread b illustration sake) can call, execute on main executing thread (thead a) @ specific given point in execution.
example usage follows:
static invoker invoker = new invoker(); static void threada() { new thread(threadb).start(); thread.sleep(...); // hypothetic alpha invoker.invoke(delegate { console.writeline("action"); }, true); console.writeline("done"); console.readline(); } static void threadb() { thread.sleep(...); // hypothetic beta invoker.execute(); } the invoker class looks this:
public class invoker { private queue<action> actions { get; set; } public invoker() { this.actions = new queue<action>(); } public void execute() { while (this.actions.count > 0) { this.actions.dequeue()(); } } public void invoke(action action, bool block = true) { manualresetevent done = new manualresetevent(!block); this.actions.enqueue(delegate { action(); if (block) done.set(); }); if (block) { done.waitone(); } } } this works fine in cases, although won't if, reason, execution (and hence set) done before waitone, in case freeze (it allows thread proceed, blocks). reproduced if alpha >> beta.
i can utilize booleans , whatnot, i'm never getting real atomic safety here. tried fixes, wouldn't work in case beta >> alpha.
i thought of locking around both invoker.execute , invoker.invoke methods guaranteed execution not occur between enqueing , waiting. however, problem lock englobes waitone, , hence never finishes (deadlock).
how should go getting absolute atomic safety in paradigm?
note: requirement work design, external dependencies. changing design not real option.
edit: did forget mention want blocking behaviour (based on bool block) until delegate executed on invoke call.
use semaphore(slim) instead of manualresetevent.
create semaphore maximum count of 1, phone call waitone() in calling thread, , phone call release() in delegate.
if you've called release(), waitone() should homecoming immediately.
make sure dispose() when you're done, preferably in using block. if block false, shouldn't create in first place (although semaphoreslim, that's not bad).
c# .net multithreading synchronization atomicity
Comments
Post a Comment