I am trying various options on working with threads. I wrote the code below, but it does not work as expected. How can I fix the code, so that the main function will correctly display the product?
using System;
using System.Threading;
namespace MultiThreads
{
class Program
{
static int prod;
public static void Main(string[] args)
{
Thread thread = new Thread(() => Multiply(2, 3));
thread.Start();
for(int i = 0; i < 10; i++) { // do some other work until thread completes
Console.Write(i + " ");
Thread.Sleep(100);
}
Console.WriteLine();
Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
Console.ReadKey(true);
}
public static void Multiply(int a, int b)
{
Thread.Sleep(2000);
prod = a * b;
}
}
}
Ignoring the fact that you should be using non-blocking tasks, volatile properties and other coroutine principals, the immediate reason your program does not work as intended is because you didn't re-join the child thread back into the parent. See Join
Without the join, the Console.WriteLine("Prod = " + prod); occurs before the assignment prod = a * b;
static int prod;
static void Main(string[] args)
{
Thread thread = new Thread(() => Multiply(2, 3));
thread.Start();
for (int i = 0; i < 10; i++)
{ // do some other work until thread completes
Console.Write(i + " ");
Thread.Sleep(100);
}
thread.Join(); // Halt current thread until the other one finishes.
Console.WriteLine();
Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
Console.ReadKey(true);
}
public static void Multiply(int a, int b)
{
Thread.Sleep(2000);
prod = a * b;
}
Related
im new to C# and i was trying to figure out async and await . for practice i was trying to start method 1 in which method 2 is called twice . method 2 takes a value and increases it by 1 each 200 ms . instead of running method 2 the program ends after the first line of method 1 .
static void Main(string[] args)
{
Method1();
}
static int Method2(int x)
{
for (int i = 0; i < 10; i++)
{
x += 1;
Console.WriteLine(x);
Thread.Sleep(200);
}
Console.WriteLine("final" + " " + x + " " + Thread.CurrentThread.ManagedThreadId);
return x;
}
static async Task Method1()
{
Console.WriteLine("1 running");
int result1 = await Task.Run(() => Method2(0));
int result2 = await Task.Run(() => Method2(result1));
Thread.Sleep(1000);
Console.WriteLine("result " + result2 * 2);
}
what am i doing wrong here ?
When calling Method() you aren't waiting on it. It returns a task object that is not acted upon, and then Main() dutifully returns, which ends the program.
You can do this in Main():
public static void Main() {
Method1().GetAwaiter().GetResult();
}
Or use async Main() instead:
public static async Task Main() {
await Method1();
}
I wrote a small programm which prints "x", then "+", then again "x" and so on.
The idea was to make it run in two threads so that the first thread prints "x" and the second prints "+". The output looks like this:
"x" -> Thread number 1
"+" -> Thread number 2
"x" -> Thread number 1enter code here
"+" -> Thread number 2
and so on..
What I wrote seems to work fine but it seems to me it is written in
very old-fashioned way:
public class Example
{
private static int count = 10;
private static int i = 0;
private static bool isOneActive = false;
private static void Run1(object o)
{
string s = o as string;
while(true)
{
if (!isOneActive)
{
Console.WriteLine("Hello from thread number: " +
Thread.CurrentThread.ManagedThreadId + " -> " + s);
isOneActive = true;
if (i++ > count) break;
}
}
}
private static void Run2(object o)
{
string s = o as string;
while(true)
{
if (isOneActive)
{
Console.WriteLine("Hello from thread number: " +
Thread.CurrentThread.ManagedThreadId + " -> " + s);
isOneActive = false;
if (i++ > count) break;
}
}
}
static void Main()
{
Thread t1 = new Thread(Run1);
Thread t2 = new Thread(Run2);
t1.Start("x");
t2.Start("+");
}
I know that now .NET has a lot of instruments for thread synchronization as for example ManualResetEvent class and Task library. So how could we write the same programm using ManualResetEvent class? Is it possible at all?
Your code isn't only old fashioned, it is very inefficient. It spins for no reason doing nothing but waiting; this is called Busy wait should be avoided whenever possible.
Better approach is to use Waithandles as noted in comments.
A naive implementation with very little change in your code will look something like the following.
public class Example
{
private static int count = 10;
private static int i = 0;
private static AutoResetEvent firstEvent = new AutoResetEvent(true);
private static AutoResetEvent secondEvent = new AutoResetEvent(false);
private static void Run1(object o)
{
string s = o as string;
while (true)
{
firstEvent.WaitOne();
Console.WriteLine("Hello from thread number: " + Thread.CurrentThread.ManagedThreadId + " -> " + s);
secondEvent.Set();
if (Interlocked.Increment(ref i) > count)
break;
}
}
private static void Run2(object o)
{
string s = o as string;
while (true)
{
secondEvent.WaitOne();
Console.WriteLine("Hello from thread number: " + Thread.CurrentThread.ManagedThreadId + " -> " + s);
firstEvent.Set();
if (Interlocked.Increment(ref i) > count)
break;
}
}
static void Main()
{
Thread t1 = new Thread(Run1);
Thread t2 = new Thread(Run2);
t1.Start("x");
t2.Start("+");
}
}
Note that firstEvent is instantiated with the initialState flag set to true which means that first thread doesn't waits initially.
Consider this example (fiddle):
static void Main(string[] args)
{
var console = new object();
int i = 0;
Task.Run(() =>
{
lock (console)
while (i++ < 10)
{
Console.Write(i);
Monitor.Pulse(console);
Monitor.Wait(console);
}
});
Task.Run(() =>
{
lock (console)
while (i < 10)
{
Console.Write('+');
Monitor.Pulse(console);
Monitor.Wait(console);
}
});
Console.ReadLine(); // Task.WaitAll might be better, remove for fiddle
}
When I run this code then nothing is shown on the console, but when I debug then it displays the output. Please explain why this happen? How I can get info when the Thread completes the task?
public class TestClass
{
static void Main()
{
ThreadPool.SetMaxThreads(5, 5);
for (int x = 0; x < 10; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(printnum), x);
}
Console.ReadKey();
}
public static void printnum(object n)
{
Console.WriteLine("Call " + n);
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
}
}
From the documentation for Console.ReadKey():
The ReadKey method waits, that is, blocks on the thread issuing the
ReadKey method, until a character or function key is pressed.
What it actually does is acquire a lock on Console.InternalSyncObject, which prevents further operations on the console.
The Console.ReadLine() method does not block the thread in this way. You can use it instead.
Reading this article I'm guessing you have .NET 4.5 installed?
The other's are right. If you do not wait for the threads to finish, you need to use Console.ReadLine. But if you do wait - as you asked - you can still use Console.ReadKey. I changed your code accordingly. Also checkout Microsofts example on how to use the ThreadPool.
static void Main(string[] args)
{
const int count = 10;
var waitHandles = new ManualResetEvent[count];
ThreadPool.SetMaxThreads(5, 5);
for (int x = 0; x < count; x++)
{
var handle = new ManualResetEvent(false);
waitHandles[x] = handle;
var worker = new MyWorker(handle, x);
ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorker.printnum), worker);
}
WaitHandle.WaitAll(waitHandles);
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
class MyWorker
{
readonly ManualResetEvent handle;
readonly int number;
public MyWorker(ManualResetEvent handle, int number)
{
this.handle = handle;
this.number = number;
}
public static void printnum(object obj)
{
var worker = (MyWorker)obj;
Console.WriteLine("Call " + worker.number);
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
// we are done
worker.handle.Set();
}
}
The key is that you have to use WaitHandles. Each thread gets one handle which is set to true when the thread finishes. In your main method you have to wait for all handles to be set to true.
I am building a small application simulating a horse race in order to gain some basic skill in working with threads.
My code contains this loop:
for (int i = 0; i < numberOfHorses; i++)
{
horsesThreads[i] = new Thread(horsesTypes[i].Race);
horsesThreads[i].Start(100);
}
In order to keep the race 'fair', I've been looking for a way to make all newly created threads wait until the rest of the new threads are set, and only then launch all of them to start running their methods (Please note that I understand that technically the threads can't be launched at the 'same time')
So basically, I am looking for something like this:
for (int i = 0; i < numberOfHorses; i++)
{
horsesThreads[i] = new Thread(horsesTypes[i].Race);
}
Monitor.LaunchThreads(horsesThreads);
Threading does not promise fairness or deterministic results, so it's not a good way to simulate a race.
Having said that, there are some sync objects that might do what you ask. I think the Barrier class (Fx 4+) is what you want.
The Barrier class is designed to support this.
Here's an example:
using System;
using System.Threading;
namespace Demo
{
class Program
{
private void run()
{
int numberOfHorses = 12;
// Use a barrier with a participant count that is one more than the
// the number of threads. The extra one is for the main thread,
// which is used to signal the start of the race.
using (Barrier barrier = new Barrier(numberOfHorses + 1))
{
var horsesThreads = new Thread[numberOfHorses];
for (int i = 0; i < numberOfHorses; i++)
{
int horseNumber = i;
horsesThreads[i] = new Thread(() => runRace(horseNumber, barrier));
horsesThreads[i].Start();
}
Console.WriteLine("Press <RETURN> to start the race!");
Console.ReadLine();
// Signals the start of the race. None of the threads that called
// SignalAndWait() will return from the call until *all* the
// participants have signalled the barrier.
barrier.SignalAndWait();
Console.WriteLine("Race started!");
Console.ReadLine();
}
}
private static void runRace(int horseNumber, Barrier barrier)
{
Console.WriteLine("Horse " + horseNumber + " is waiting to start.");
barrier.SignalAndWait();
Console.WriteLine("Horse " + horseNumber + " has started.");
}
private static void Main()
{
new Program().run();
}
}
}
[EDIT] I just noticed that Henk already mentioned Barrier, but I'll leave this answer here because it has some sample code.
I'd be looking at a ManualResetEvent as a gate; inside the Thread, decrement a counter; if it is still non-zero, wait on the gate; otherwise, open the gate. Basically:
using System;
using System.Threading;
class Program
{
static void Main()
{
ManualResetEvent gate = new ManualResetEvent(false);
int numberOfThreads = 10, pending = numberOfThreads;
Thread[] threads = new Thread[numberOfThreads];
ParameterizedThreadStart work = name =>
{
Console.WriteLine("{0} approaches the tape", name);
if (Interlocked.Decrement(ref pending) == 0)
{
Console.WriteLine("And they're off!");
gate.Set();
}
else gate.WaitOne();
Race();
Console.WriteLine("{0} crosses the line", name);
};
for (int i = 0; i < numberOfThreads; i++)
{
threads[i] = new Thread(work);
threads[i].Start(i);
}
for (int i = 0; i < numberOfThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("all done");
}
static readonly Random rand = new Random();
static void Race()
{
int time;
lock (rand)
{
time = rand.Next(500,1000);
}
Thread.Sleep(time);
}
}
I am trying to test a simply designed code piece on Microsoft HPC. It looks like the job is not completing the all code. My test method might be wrong though. I am just printing out some check points. Here is the code:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
class S
{
static void Main()
{
pcount = Environment.ProcessorCount;
Console.WriteLine("Proc count = " + pcount);
ThreadPool.SetMinThreads(4, -1);
ThreadPool.SetMaxThreads(4, -1);
// System.Threading.Thread.Sleep(20000);
Console.WriteLine("check point 0 ");
t1 = new Task(A, 1);
t2 = new Task(A, 2);
t3 = new Task(A, 3);
t4 = new Task(A, 4);
Console.WriteLine("Starting t1 " + t1.Id.ToString());
t1.Start();
Console.WriteLine("Starting t2 " + t2.Id.ToString());
t2.Start();
Console.WriteLine("Starting t3 " + t3.Id.ToString());
t3.Start();
Console.WriteLine("Starting t4 " + t4.Id.ToString());
t4.Start();
// Console.ReadLine();
}
static void A(object o)
{
Console.WriteLine("check point A ");
B(o);
}
static void B(object o)
{
int temp = (int)o;
Console.WriteLine("check point B ");
if (temp == 1)
{
C(o);
}
else
{
F(o);
}
}
static void C(object o)
{
Console.WriteLine("check point C ");
D(o);
}
static void D(object o)
{
int temp = (int)o;
Console.WriteLine("check point D " + temp);
if (temp == 2)
{
F(o);
}
else
{
E(o);
}
}
static void E(object o)
{
Console.WriteLine("check point E ");
}
static void F(object o)
{
Console.WriteLine("check point F ");
G(o);
}
static void G(object o)
{
Console.WriteLine("check point G ");
}
static Task t1, t2, t3, t4;
static int pcount;
}
In the job output, it is not printing till to the end. Printout ends randomly at any point( in a random function). Ok, I understand that, It may not able to print everything since the execution is faster than printing (possible explanation). But, if I try to place breakpoints and try to debug by attaching to process, it only hits the breakpoints in the first parts of the code. Looks like hitting the same range as test print out has. How I can make sure that the code runs through the end, so that breakpoints at any point can be hit?
A Task is designed to run on a so-called background thread. That means: If the main thread terminates, so will the background thread. So as soon as your Main() method completes, all threads (and therefore all Tasks) get terminated, and your program ends.
The solution is to wait for your Tasks to complete.
static void Main()
{
pcount = Environment.ProcessorCount;
Console.WriteLine("Proc count = " + pcount);
ThreadPool.SetMinThreads(4, -1);
ThreadPool.SetMaxThreads(4, -1);
// System.Threading.Thread.Sleep(20000);
Console.WriteLine("check point 0 ");
t1 = new Task(A, 1);
t2 = new Task(A, 2);
t3 = new Task(A, 3);
t4 = new Task(A, 4);
Console.WriteLine("Starting t1 " + t1.Id.ToString());
t1.Start();
Console.WriteLine("Starting t2 " + t2.Id.ToString());
t2.Start();
Console.WriteLine("Starting t3 " + t3.Id.ToString());
t3.Start();
Console.WriteLine("Starting t4 " + t4.Id.ToString());
t4.Start();
// Console.ReadLine();
t1.Wait();
t2.Wait();
t3.Wait();
t4.Wait();
}