Reputation: 9146
I have a C# code with 2 threads. It calls the print method, but It always have the same time .. why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MultiThreading
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(new Program().print));
Thread thread2 = new Thread(new ThreadStart(new Program().print));
thread.Name = "Thread1";
thread2.Name = "thread2";
thread.Start();
thread2.Start();
}
public void print()
{
Random r = new Random();
int time = r.Next(3000);
System.Console.WriteLine(Thread.CurrentThread.Name + ", " + (double)time/1000 + " secs!");
Thread.Sleep(time);
}
}
}
Ok so I hame 2 threads, and each one have the "print" delegate.
print generates a number time
what what time
seconds.
thread
and thread2
generates the same time always, how to fix it?
Upvotes: 1
Views: 1292
Reputation: 488
Call Randomize()
before thread startups.
This generates new seeds for your random functions to use!
Upvotes: 0
Reputation: 4376
Your confusion is not because of threads but because of the Random Number generator.
MSDN says :
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.
Try replacing your new Random line with this and see the difference.
Random r = new Random(Thread.CurrentThread.ManagedThreadId);
I have just added a new random seed so that every thread gets a different value.
Edit: Instead of ManagedThreadId, you can use any other value of your choosing for the seed value. You need to make sure it is different to get different sequences of random numbers from your Random object. As to why ManagedThreadId is not a very good choice, please see comment below.
Upvotes: 2
Reputation: 11
i guess, the problem is the call of the Random() method! Try using different seeds with every Thread otherwise you always get the same random number!
Upvotes: 0
Reputation: 148160
You can use System.Threading.Thread.Sleep method between to thread start methods to start them with interval.
thread.Start();
System.Threading.Thread.Sleep(100);
thread2.Start();
Upvotes: 1