c# - How to block new threads until all threads are created and started -
i building small application simulating horse race in order gain basic skill in working threads.
my code contains loop:
(int = 0; < numberofhorses; i++) { horsesthreads[i] = new thread(horsestypes[i].race); horsesthreads[i].start(100); }
in order keep race 'fair', i've been looking way make newly created threads wait until rest of new threads set, , launch of them start running methods (please note understand technically threads can't launched @ 'same time')
so basically, looking this:
(int = 0; < numberofhorses; i++) { horsesthreads[i] = new thread(horsestypes[i].race); } monitor.launchthreads(horsesthreads);
the barrier
class designed support this.
here's example:
using system; using system.threading; namespace demo { class program { private void run() { int numberofhorses = 12; // use barrier participant count 1 more // number of threads. 1 main thread, // used signal start of race. using (barrier barrier = new barrier(numberofhorses + 1)) { var horsesthreads = new thread[numberofhorses]; (int = 0; < numberofhorses; i++) { int horsenumber = i; horsesthreads[i] = new thread(() => runrace(horsenumber, barrier)); horsesthreads[i].start(); } console.writeline("press <return> start race!"); console.readline(); // signals start of race. none of threads called // signalandwait() return call until *all* // participants have signalled barrier. barrier.signalandwait(); console.writeline("race started!"); console.readline(); } } private static void runrace(int horsenumber, barrier barrier) { console.writeline("horse " + horsenumber + " waiting start."); barrier.signalandwait(); console.writeline("horse " + horsenumber + " has started."); } private static void main() { new program().run(); } } }
[edit] noticed henk mentioned barrier
, i'll leave answer here because has sample code.
Comments
Post a Comment