473,770 Members | 1,994 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading / random number problem

Hi,

My R&D department has asked me to look at threading in a Web Service written
in C#, so I came up with the following code:

using System;
using System.Componen tModel;
using System.Threadin g;
using System.Web.Serv ices;

namespace CWSThreading
{
public class CThreading : System.Web.Serv ices.WebService
{
private double mdThread1;
private double mdThread2;

public CThreading()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeCompo nent();
}

[WebMethod]
public string TestThreading()
{
string strOutput = "";

Thread thread1 = new Thread(new ThreadStart(Ran domNumber1));
thread1.Start() ;
strOutput += "Result from 1st thread: " + mdThread1.ToStr ing() + "\n";

Thread thread2 = new Thread(new ThreadStart(Ran domNumber2));
thread2.Start() ;
strOutput += "Result from 2nd thread: " + mdThread2.ToStr ing() + "\n";

return strOutput;
}

protected void RandomNumber1()
{
System.Random rndNumber = new Random((int)Dat eTime.Now.Ticks );
mdThread1 = rndNumber.NextD ouble();
}

protected void RandomNumber2()
{
System.Random rndNumber = new Random((int)Dat eTime.Now.Ticks );
mdThread2 = rndNumber.NextD ouble();
}
}
}

This is being called by a Windows app to which a web reference has been
added pointing to the above web service. A simple form with a button runs
the following code:

using TestWSThreading .wsThreading;

private void cmdTestWSThread ing_Click(objec t sender, System.EventArg s e)
{
wsThreading.CTh reading wsTestThreading = new CThreading();
string strOutput = wsTestThreading .TestThreading( );
MessageBox.Show (strOutput);
wsTestThreading = null;
}
If I set a breakpoint anywhere in the above code which causes me to step
through it, it always returns different random numbers e.g.:

Result from 1st thread: 0.5133791689357 62
Result from 2nd thread: 0.2027999298660 08

However, if I remove the breakpoint so that the web service runs "normally",
I always get the following result:

Result from 1st thread: 0
Result from 2nd thread: 0

Any assistance gratefully received.

Best regards,

Mark Rae
Nov 15 '05 #1
11 1840
Comments inline:

"Mark Rae" <ma**@markrae.c o.uk> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Hi,

My R&D department has asked me to look at threading in a Web Service written in C#, so I came up with the following code:

using System;
using System.Componen tModel;
using System.Threadin g;
using System.Web.Serv ices;

namespace CWSThreading
{
public class CThreading : System.Web.Serv ices.WebService
{
private double mdThread1;
private double mdThread2;

public CThreading()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeCompo nent();
}

[WebMethod]
public string TestThreading()
{
string strOutput = "";

Thread thread1 = new Thread(new ThreadStart(Ran domNumber1));
thread1.Start() ;
strOutput += "Result from 1st thread: " + mdThread1.ToStr ing() + "\n";

Thread thread2 = new Thread(new ThreadStart(Ran domNumber2));
thread2.Start() ;
strOutput += "Result from 2nd thread: " + mdThread2.ToStr ing() + "\n";

return strOutput;
}
The main issue here as far as I see is that you start the threads and then
immediately read the variables that the threads are supposed to assign
values. There is no guarantee that the threads execute before you read the
variables. To fix this, you should wait for the threads to complete before
you access the variables:

// start both threads
Thread thread1 = new Thread(new ThreadStart(Ran domNumber1));
thread1.Start() ;
Thread thread2 = new Thread(new ThreadStart(Ran domNumber2));
thread2.Start() ;

// wait for thread1 to complete, read its results
thread1.Join();
strOutput += "Result from 1st thread: " + mdThread1.ToStr ing() + "\n";

// wait for thread2 to complete, read its results
thread2.Join();
strOutput += "Result from 2nd thread: " + mdThread2.ToStr ing() + "\n";

If I set a breakpoint anywhere in the above code which causes me to step
through it, it always returns different random numbers e.g.:

Result from 1st thread: 0.5133791689357 62
Result from 2nd thread: 0.2027999298660 08

However, if I remove the breakpoint so that the web service runs "normally", I always get the following result:

Result from 1st thread: 0
Result from 2nd thread: 0

Any assistance gratefully received.


The results are highly unpredictable unless you do some sort of
synchronization . You're getting 0s because the main thread reads the
variables before the background threads have a chance to execute. Use
Thread.Join to synchronize the threads.

Sami
www.capehill.net
Nov 15 '05 #2
"Sami Vaaraniemi" <sa************ ***@jippii.fi> wrote in message
news:c2******** **@phys-news1.kolumbus. fi...
Comments inline:
Thanks for the response.
The main issue here as far as I see is that you start the threads and then
immediately read the variables that the threads are supposed to assign
values. There is no guarantee that the threads execute before you read the
variables. To fix this, you should wait for the threads to complete before
you access the variables:

// start both threads
Thread thread1 = new Thread(new ThreadStart(Ran domNumber1));
thread1.Start() ;
Thread thread2 = new Thread(new ThreadStart(Ran domNumber2));
thread2.Start() ;

// wait for thread1 to complete, read its results
thread1.Join();
strOutput += "Result from 1st thread: " + mdThread1.ToStr ing() + "\n";

// wait for thread2 to complete, read its results
thread2.Join();
strOutput += "Result from 2nd thread: " + mdThread2.ToStr ing() + "\n";
I did as you suggested. Now, I don't get zeroes any more, but now the two
threads always return the same value e.g.

Result from 1st thread: 0.5337773345102 45
Result from 2nd thread: 0.5337773345102 45
The results are highly unpredictable unless you do some sort of
synchronization . You're getting 0s because the main thread reads the
variables before the background threads have a chance to execute. Use
Thread.Join to synchronize the threads.


I'm obviously missing something else... :-)

Mark
Nov 15 '05 #3
Random's being seeded from the current time, and both your threads are
essentially executing at the same time (give or take) so it's possible
they're getting seeded with the same number. It does seem a bit strange
(since you'd think that Tick would never return the same value even if the
execution times are very similar). That would be my best guess.

Steve

"Mark Rae" <ma**@markrae.c o.uk> wrote in message
news:Oa******** ******@TK2MSFTN GP11.phx.gbl...
"Sami Vaaraniemi" <sa************ ***@jippii.fi> wrote in message
news:c2******** **@phys-news1.kolumbus. fi...
Comments inline:


Thanks for the response.
The main issue here as far as I see is that you start the threads and then immediately read the variables that the threads are supposed to assign
values. There is no guarantee that the threads execute before you read the variables. To fix this, you should wait for the threads to complete before you access the variables:

// start both threads
Thread thread1 = new Thread(new ThreadStart(Ran domNumber1));
thread1.Start() ;
Thread thread2 = new Thread(new ThreadStart(Ran domNumber2));
thread2.Start() ;

// wait for thread1 to complete, read its results
thread1.Join();
strOutput += "Result from 1st thread: " + mdThread1.ToStr ing() + "\n";

// wait for thread2 to complete, read its results
thread2.Join();
strOutput += "Result from 2nd thread: " + mdThread2.ToStr ing() + "\n";


I did as you suggested. Now, I don't get zeroes any more, but now the two
threads always return the same value e.g.

Result from 1st thread: 0.5337773345102 45
Result from 2nd thread: 0.5337773345102 45
The results are highly unpredictable unless you do some sort of
synchronization . You're getting 0s because the main thread reads the
variables before the background threads have a chance to execute. Use
Thread.Join to synchronize the threads.


I'm obviously missing something else... :-)

Mark

Nov 15 '05 #4

"Mark Rae" <ma**@markrae.c o.uk> wrote in message
news:Oa******** ******@TK2MSFTN GP11.phx.gbl...
I did as you suggested. Now, I don't get zeroes any more, but now the two
threads always return the same value e.g.

Result from 1st thread: 0.5337773345102 45
Result from 2nd thread: 0.5337773345102 45
The results are highly unpredictable unless you do some sort of
synchronization . You're getting 0s because the main thread reads the
variables before the background threads have a chance to execute. Use
Thread.Join to synchronize the threads.


I'm obviously missing something else... :-)


The reason for the same number being returned is that the .NET Random number
generator is a so-called pseudo-random generator. Given the same seed it
always generates the same sequence of "random" numbers. So the numbers are
not really random (whatever that means), they are just evenly distributed.
You are getting the same random number because the threads happen to
initialize the generator with the same seed value.

To ensure unique seeds for the random number generator, you could use e.g.,
the thread ID (AppDomain.GetC urrentThreadId or Thread.GetHashC ode()) as the
seed. You could also combine DateTime.Now.Ti cks with the thread ID somehow.

Sami
www.capehill.net
Nov 15 '05 #5
Considering that

DateTime.Ticks:
"The value of this property is the number of 100-nanosecond intervals that
have elapsed since 12:00 A.M., January 1, 0001."

and 3GHz computers have clock cycles of ~3 nanoseconds it's quite possible
to get a random initiated with the same seed if you do it close enough.

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #6
"Steve McLellan" <sj*@fixerlabs. com.NOSPAM> wrote in message
news:uj******** *****@tk2msftng p13.phx.gbl...
Random's being seeded from the current time, and both your threads are
essentially executing at the same time (give or take) so it's possible
they're getting seeded with the same number. It does seem a bit strange
(since you'd think that Tick would never return the same value even if the
execution times are very similar). That would be my best guess.


Thanks for the response. Yes, the reason I was using the code

System.Random rndNumber = new Random((int)Dat eTime.Now.Ticks );

was in the hope that it would always generate a different number...
Nov 15 '05 #7
"Sami Vaaraniemi" <sa************ ***@jippii.fi> wrote in message
news:c2******** **@phys-news1.kolumbus. fi...

Thanks for the response.
The reason for the same number being returned is that the .NET Random number generator is a so-called pseudo-random generator. Given the same seed it
always generates the same sequence of "random" numbers. So the numbers are
not really random (whatever that means), they are just evenly distributed.
You are getting the same random number because the threads happen to
initialize the generator with the same seed value.
I understand.
To ensure unique seeds for the random number generator, you could use e.g., the thread ID (AppDomain.GetC urrentThreadId or Thread.GetHashC ode()) as the seed. You could also combine DateTime.Now.Ti cks with the thread ID

somehow.

Yes - I changed part of the code to:

thread1.Join();
strOutput += "Result from 1st thread: " + Convert.ToStrin g((mdThread1 /
thread1.GetHash Code()) * 1000) + "\n";
thread2.Join();
strOutput += "Result from 2nd thread: " + Convert.ToStrin g((mdThread2 /
thread2.GetHash Code()) * 1000) + "\n";

and it now produces different (albeit very similar!) numbers every time.

Job done - thanks for your help.

Mark
Nov 15 '05 #8
"Morten Wennevik" <Mo************ @hotmail.com> wrote in message
news:op******** ******@msnews.m icrosoft.com...
Considering that

DateTime.Ticks:
"The value of this property is the number of 100-nanosecond intervals that
have elapsed since 12:00 A.M., January 1, 0001."

and 3GHz computers have clock cycles of ~3 nanoseconds it's quite possible
to get a random initiated with the same seed if you do it close enough.


You're right - I hadn't considered that! It's been a while since I
encountered a problem because my development machine was too fast... :-)
Nov 15 '05 #9
Mark Rae <ma**@markrae.c o.uk> wrote:
Yes - I changed part of the code to:

thread1.Join();
strOutput += "Result from 1st thread: " + Convert.ToStrin g((mdThread1 /
thread1.GetHash Code()) * 1000) + "\n";
thread2.Join();
strOutput += "Result from 2nd thread: " + Convert.ToStrin g((mdThread2 /
thread2.GetHash Code()) * 1000) + "\n";

and it now produces different (albeit very similar!) numbers every time.


That's not changed the seed at all - that's just divided the *result*
by the hash code.

Instead, it would be better to have *one* random number generator, and
serialize access to it. You only need to have one seed then, and using
the current time for that is reasonable.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2506
by: Virus | last post by:
Ok well what I am trying to do is have 1.) the background color to change randomly with 5 different colors.(change on page load) 2,) 10 different quotes randomly fadeing in and out in random spots on the webpage. with a delay timer on them, so they keep changing as the page is open. Not random each time the page is loaded. If anyone can help it would be greatly appreaciated, I have tried many of
10
2911
by: Sonoman | last post by:
Hi all: I am trying to write a simple program that simulates asking several persons their birth day and it counts how many persons are asked until two have the same birth day. The problem that I have is that the first loop I get a sequence of random numbers untuil I get a match, BUT then on the following loops I get the SAME random(?) sequence. I am using rand(). I do not want to get too fancy with the random number generator, but is there...
3
1475
by: Manuel | last post by:
I've playing around with multi-threading applications lately. The main problem I have is that when I create a file/table/whatever I need a unique name. The only way I could come up with, is asking for a temporary file (System.IO.Path.GetTempFileName) and that file name would be the unique character string I was looking for. The same goes for the log report files. I have to use the temp file name as seed for the random, wait that amount...
40
2823
by: RadiationX | last post by:
I have a problem that I really don't understand at all. In my previous post I could get started on my projects I just had a few problems with syntax errors. This problem is something that I don't conceptually understand very well. Here it is: Π – the ratio of the circumference of a circle to its diameter – is one of the most common and important constants in mathematics. It is an irrational number (a real number that cannot be...
10
2187
by: Janto Dreijer | last post by:
I have been having problems with the Python 2.4 and 2.5 interpreters on both Linux and Windows crashing on me. Unfortunately it's rather complex code and difficult to pin down the source. So I've been trying to reduce the code. In the process it's started to crash in different ways. I'm not sure if any of it is related. The following is only crashing Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on win32 in two different(?) ways.
9
1864
by: cgwalters | last post by:
Hi, I've recently been working on an application which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this CPU-intensive work in another thread, but of course this won't work because of Python's GIL. There's a lot of past discussion on this, and I want to bring it up again because with the work on Python 3000, I think it is worth trying
2
965
by: JonathanB | last post by:
I have a multi-access problem that I'm pretty sure needs to be solved with threading, but I'm not sure how to do it. This will be my first foray into threading, so I'm a little confused by all of the new landscape. So, I'm going to lay out the problem I'm facing and if someone could point me towards a good example of what I need to do, that would be great. I read THE tutorial, and while it made since to me in an esoteric sense, I'm not...
13
2815
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: unsigned long Random( unsigned long num )
126
6748
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard: http://www.cse.wustl.edu/~schmidt/ACE.html the same way that the STL (and subsequently BOOST) have been subsumed? Since it already runs on zillions of platforms, they have obviously worked most of the kinks out of the generalized threading and processes idea (along with many...
0
10259
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10101
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.