I made a little example program that counts numbers using two threads. It also prints a second number next to the count so I can see which thread printed which number.
Now my goal is to make both threads immediately stop once one of them counted 7. I don't know how to go about it. I thought about passing a thread array as a parameter to Counter
and then use a foreach loop to abort both threads. The problem is that t0
might be executing it and calls t0.Abort()
and thus t1.Abort()
won't be called anymore.
public static int count = 0;
private static object lockObject = new object();
static void Main(string[] args) {
Thread t0 = new Thread(() => Counter(1, 10));
Thread t1 = new Thread(() => Counter(10, 20));
t0.Start();
t1.Start();
t0.Join();
t1.Join();
Console.ReadLine();
}
public static void Counter(int k, int m) {
for(int i = k; i < m; i++) {
lock (lockObject) {
count++;
Console.WriteLine(count + " " + i);
if (i == 7) {
/*
* Code that will kill thread t0 and t1
*/
}
}
}
}
The output should be something like
1 1
2 2
3 10
4 11
5 12
6 13
7 14
Does someone have suggestions how to kill both t0
and t1
?