c# - How do I perform both a read and a write of a boolean in one atomic operation? -
let's have method gets called multiple threads
public class multithreadclass { public void gogogo() { // method implementation } private volatile bool running; } in gogogo(), want check if running true, , if so, return method. however, if false, want set true , continue method. solution see following:
public class multithreadclass { public void gogogo() { lock (this.locker) { if (this.running) { return; } this.running = true; } // rest of method this.running = false; } private volatile bool running; private readonly object locker = new object(); } is there way this? i've found out if leave out lock, running false 2 different threads, set true, , rest of method execute on both threads simultaneously.
i guess goal have rest of method execute on single thread (i don't care one) , not executed other threads, if of them (2-4 in case) call gogogo() simultaneously.
i lock on entire method, method run slower then? needs run fast possible, part of on 1 thread @ time.
(details: have dicionary of concurrentqueue's contain "results" have "job names". trying dequeue 1 result per key in dictionary (one result per job name) , call "complete result" sent event subscribers. results sent via event class, , event raised multiple threads (one per job name; each job raises "result ready" event on it's own thread)
you can use interlocked.compareexchange if change bool int:
private volatile int running = 0; if(interlocked.compareexchange(ref running, 1, 0) == 0) { //running changed false true }
Comments
Post a Comment