c# - I can start threads with switches but can't end them -
i want start number of threads based on number of threads computer running program have.
i tried doing switches seems can't end threads.
this main thread , doesn't work, says threads out of context on 2nd switch
is there can add or should use different method altogether?
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.collections; using system.io; using system.diagnostics; using system.threading; using system.security.principal; namespace yahtzee_datamine { class program { public static random dicevalue = new random(); public static int numberofdie = new int(); public static int numberofsides = new int(); private static system.object lockthis = new system.object(); public static decimal percent = new decimal(); public static consolecolor oldcolor = console.foregroundcolor; static void main(string[] args) { while (true) { getinfo(); int processorcount = environment.processorcount; console.writeline(processorcount); if (processorcount > 7) { processorcount = 7; } switch (processorcount) { case 7: thread rolls6 = new thread(rolling2); rolls6.start(); goto case 6; case 6: thread rolls5 = new thread(rolling3); rolls5.start(); goto case 5; case 5: thread rolls4 = new thread(rolling4); rolls4.start(); goto case 4; case 4: thread rolls3 = new thread(rolling5); rolls3.start(); goto case 3; case 3: thread rolls2 = new thread(rolling6); rolls2.start(); goto case 1; case 2: case 1: thread rolls1 = new thread(rolling7); rolls1.start(); break; } while (true) { char quit = quit = console.readkey().keychar; if (quit == 'q') { console.writeline("\rterminated"); break; } } switch (processorcount) { case 7: rolls6.abort(); goto case 6; case 6: rolls5.abort(); goto case 5; case 5: rolls4.abort(); goto case 4; case 4: rolls3.abort(); goto case 3; case 3: rolls2.abort(); goto case 1; case 2: case 1: rolls1.abort(); break; } } } public static void getinfo() { if (windowsidentity.getcurrent().owner.iswellknown(wellknownsidtype.builtinadministratorssid) == false) { console.writeline("you not running elevated administrative access."); console.writeline("please restart , run program administrative access"); } #region gettingnumberofdie while (true) { console.writeline("how many die roll? type q quit"); string howmanydie = console.readline(); try { int.tryparse(howmanydie, out numberofdie); if (numberofdie < 2) { console.writeline("please enter integer greater 1"); continue; } break; } catch { console.writeline("please enter number or press q quit"); continue; } } #endregion #region gettingnumberofsides while (true) { console.writeline("how many sides want each die have?"); string howmanysides = console.readline(); try { int.tryparse(howmanysides, out numberofsides); if (numberofsides < 2) { console.writeline("please enter integer greater 1"); continue; } break; } catch { console.writeline("please enter number or press q quit"); continue; } } #endregion #region gettingpercent int percentcounter = 1; percent = (1m / (numberofsides)); decimal percentmultiplier = percent; while (percentcounter < numberofdie) { percent = percent * percentmultiplier; percentcounter++; } percent = percent * 100; #endregion console.writeline("with " + numberofdie + ", " + numberofsides + " sided die, have " + percent + '%' + " chance of getting yahtzee given roll"); console.writeline("press key commence"); console.readkey(); } static int seed = environment.tickcount; static readonly threadlocal<random> random = new threadlocal<random>(() => new random(interlocked.increment(ref seed))); public static int rand() { return random.value.next(numberofsides); } private static void rolling1() { console.writeline("thread1 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll[counteryaht] != valuesofroll[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread1 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #endregion #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = (numberofrolls).tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 1"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } } private static void rolling2() { console.writeline("thread2 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll[counteryaht] != valuesofroll[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread2 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #endregion #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = numberofrolls.tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 2"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } } private static void rolling3() { console.writeline("thread3 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll3 = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll3.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll3[counteryaht] != valuesofroll3[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } #endregion if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread3 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = numberofrolls.tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 3"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } } private static void rolling4() { console.writeline("thread4 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll[counteryaht] != valuesofroll[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } #endregion if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread4 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = numberofrolls.tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 4"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } } private static void rolling5() { console.writeline("thread5 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll[counteryaht] != valuesofroll[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } #endregion if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread5 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = numberofrolls.tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 5"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } } private static void rolling6() { console.writeline("thread6 started"); while (true) { #region rolls stopwatch rolltime = new stopwatch(); rolltime.start(); uint64 numberofrolls = 0; while (true) { numberofrolls++; int counter = 0; int[] valuesofroll = new int[numberofdie]; #region roll while (counter < numberofdie) { valuesofroll.setvalue((rand() + 1), counter); counter++; } #region isityahtzee? boolean isityahtzee = true; int counteryaht = 1; while (counteryaht < numberofdie) { if (valuesofroll[counteryaht] != valuesofroll[0]) { isityahtzee = false; counteryaht++; break; } else { counteryaht++; continue; } } #endregion if ((numberofrolls % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread6 has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } #region ifyahtzee if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = numberofdie + "," + numberofsides + "," + (numberofdie * numberofsides) + "," + numberofrolls + "," + percent + "%" + "," + (percent * numberofrolls) + "," + time + "," + timesec + "," + (numberofrolls / rolltime.elapsed.totalseconds); string linesb = numberofrolls.tostring(); lock (lockthis) { system.io.streamwriter filea = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\all.txt", true); filea.writeline(linesa); filea.close(); system.io.streamwriter fileb = new system.io.streamwriter(directory.getcurrentdirectory().tostring() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", true); fileb.writeline(linesb); fileb.close(); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread 6"); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } #endregion #endregion #endregion } }
it looks need learn more of basics of c# before try complicated. you've got interesting mix of clever , basic code. appears you've copy-and-pasted lot elsewhere.
the basic issue you're having you're declaring thread variables (thread rolls6 = new thread(rolling2);
) within scope of first switch (processorcount)
statement. when comes second 1 variables don't exist. move variable declarations higher in method make them visible both, that's going mistake. calling thread.abort
bad practice. need lets thread terminate normally.
in nutshell threads should see when should end , should respond accordingly.
the basic way code looks this:
private static void rolling(cancellationtoken ct) { while (true) { if (ct.iscancellationrequested) { console.writeline("done thread " + n); break; } /* stuff here, let code loop */ } }
the code keeps checking cancellationtoken
see if iscancellationrequested
has been set or not.
that's how end thread cleanly.
now have gotten rid of of rolling{n}
methods , replaced them single method signature void rolling(int n, int numberofdie, int numberofsides, double percent, cancellationtoken ct)
. i've tried rid of global variables (which bad) , i'm following cancellationtoken
pattern.
to start threads i've gotten of switch statements. thread creation looks this:
cancellationtokensource[] ctss = enumerable .range(1, processorcount) .select(n => { var cts = new cancellationtokensource(); var t = new thread(() => rolling(n, numberofdie, numberofsides, percent, cts.token)); t.start(); return cts; }) .toarray();
to cancel of threads code becomes:
foreach (var cts in ctss) { cts.cancel(); }
...and ct.iscancellationrequested
becomes true in rolling
method , shut down themselves.
that's approach should taking.
here's full code:
private static system.object lockthis = new system.object(); public static consolecolor oldcolor = console.foregroundcolor; private static int seed = environment.tickcount; private static readonly threadlocal<random> random = new threadlocal<random>(() => new random(interlocked.increment(ref seed))); static void main(string[] args) { var x = getvalue("how many die roll?", 1); if (x.hasvalue) { var y = getvalue("how many sides want each die have?", 2); if (y.hasvalue) { int numberofdie = x.value; int numberofsides = y.value; double percent = 100 * math.pow(1.0 / numberofsides, numberofdie); console.writeline("with " + numberofdie + ", " + numberofsides + " sided die, have " + percent + '%' + " chance of getting yahtzee given roll"); console.writeline("press key commence"); console.readline(); int processorcount = system.math.min(environment.processorcount, 8); console.writeline(processorcount); cancellationtokensource[] ctss = enumerable .range(1, processorcount) .select(n => { var cts = new cancellationtokensource(); var t = new thread(() => rolling(n, numberofdie, numberofsides, percent, cts.token)); t.start(); return cts; }) .toarray(); while (true) { string quit = console.readline().substring(0, 1).toupper(); if (quit == "q") { console.writeline(environment.newline, "terminated"); break; } } foreach (var cts in ctss) { cts.cancel(); } } } } private static int? getvalue(string prompt, int minimum) { while (true) { console.writeline(prompt + " type q quit"); var input = console.readline().substring(0, 1).toupper(); if (input == "q") { return null; } int output; if (int.tryparse(input, out output)) { if (output < minimum) { console.writeline("please enter integer greater or equal " + minimum); continue; } else { return output; } } } } private static void rolling(int n, int numberofdie, int numberofsides, double percent, cancellationtoken ct) { console.writeline("thread" + n + " started"); stopwatch rolltime = stopwatch.startnew(); long numberofrolls = 0; while (true) { if (ct.iscancellationrequested) { console.writeline("done thread " + n); break; } int[] valuesofroll = enumerable .range(0, numberofdie) .select(x => random.value.next(numberofsides) + 1) .toarray(); boolean isityahtzee = valuesofroll.all(x => x == valuesofroll[0]); if ((numberofrolls++ % 100000000) == 0) { console.foregroundcolor = consolecolor.green; console.writeline("thread" + n + " has rolled " + numberofrolls); console.foregroundcolor = oldcolor; } if (isityahtzee == true) { rolltime.stop(); string time = rolltime.elapsed.tostring(); string timesec = rolltime.elapsed.totalseconds.tostring(); string linesa = string.format( "{0},{1},{2},{3},{4}%,{5},{6},{7},{8}", numberofdie, numberofsides, numberofdie * numberofsides, numberofrolls, percent, percent * numberofrolls, time, timesec, numberofrolls / rolltime.elapsed.totalseconds); string linesb = (numberofrolls).tostring(); lock (lockthis) { file.appendalllines(directory.getcurrentdirectory() + "\\all.txt", new[] { linesa }); file.appendalllines(directory.getcurrentdirectory() + "\\avg_" + numberofdie + "x" + numberofsides + ".txt", new[] { linesb }); } console.foregroundcolor = consolecolor.red; console.writeline(numberofrolls + " file has been save thread " + n); console.foregroundcolor = oldcolor; numberofrolls = 0; break; } } }
Comments
Post a Comment