i want have static (global) pool of calculators going accessed lot of different threads. after researching found out elements of arrays threadsafe. thought idea store diffrent calculators (amount unknown until runtime) in static array (calculator[] calculators).
how ensure 1 calculator being used 1 calculator?
read whole msdn documentation don't post "only" links please.
i have thought bool array "locked" can't find way implement threadsafe.
my code far:
internal static class calculators { private static semaphore pool; private static bool[] locked; private static calcs[] neuralnetworks; private static thread[] threads; internal static calculators(){ int number = globals.number; pool = new semaphore(number, number); locked = new bool[number]; calcs = new calcs[number]; threads = new thread[number]; (int index = 0; index < number; index++) { // neuralnetworks unlocked default locked[index] = false; // generate 1 network per "countthreads" calcs[index] = globals.calcobj; // generate 1 thread each neural network threads[index] = new thread(new threadstart()); } } private int whichcalculators() { int index; (index = 0; index < countthreads; index++) { if (locked[index] == false) { locked[index] = true; return index; } } throw new exception("calculators called, there weren't networks unused"); } }
code update: should work, if call "whichcalculator()" in method?
private static void dostuff() { pool.waitone(); monitor.enter(thislock); try { int whichcalculator = whichcalculator(); locked[whichcalculator] = true; lock (calculators[whichcalculator]) { monitor.exit(thislock); // stuff locked[whichcalculator] = false; } } catch { monitor.exit(thislock); } //calculate(); pool.release(); } question 2: right assume, static constructor going executed (but before) first time class or member of going accessed?
yes have use lock. array , every instance of calculator again.
if can fill array before start multithreaded section of code need not lock array (only reading doesn't make problems due static content) resizing array need lock every access (writing , reading). code this:
calculator calc = null; lock(calculators) { calc = calculators[0]; } lock(calc) { // ... stuff } this way array isn't longer locked needed , can lock calculator itself.
Comments
Post a Comment