473,320 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

rand() and threads

93
Hi,
I made this simple program.

Expand|Select|Wrap|Line Numbers
  1. UINT Func(void * x)
  2. {
  3.     cout << rand() << endl;
  4.     return 0;
  5. }
  6.  
  7. int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
  8. {
  9.     int nRetCode = 0;
  10.  
  11.     srand(time(0));
  12.  
  13.     while(1)
  14.     {
  15.         Sleep(10);
  16.         AfxBeginThread(Func, NULL);
  17.         //Func(NULL);
  18.     }
  19.  
  20.     return nRetCode;
  21. }
  22.  
  23.  
Now, All that is printed on the console is a steady stream of 41s. I guess this is because the rand() function is somehow "reset" for different threads. But waht I want to get is actual random numbers for each thread. How can I achieve this? Thanks.
Oct 18 '07 #1
8 3766
Banfa
9,065 Expert Mod 8TB
Write you own thread re-entrant rand function.

You should be able to find a workable algorithm using Google or Wikipedia.

You can make the function thread re-entrant by using a CriticalSection.
Oct 18 '07 #2
DumRat
93
I did modify it by using critical sections, but still the same problem. I don't feel like writing my own rand function. Isn't there anyway to get this done?

here's the modified version:

Expand|Select|Wrap|Line Numbers
  1. CRITICAL_SECTION crtsec;
  2.  
  3. static int Rand()
  4. {
  5.     return rand();
  6. }
  7.  
  8. UINT Func(void * x)
  9. {
  10.     EnterCriticalSection(&crtsec);
  11.     srand(timeGetTime());
  12.     cout << rand() << endl;
  13.     LeaveCriticalSection(&crtsec);
  14.     return 0;
  15. }
  16.  
  17. int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
  18. {
  19.     InitializeCriticalSection(&crtsec);
  20.     int nRetCode = 0;
  21.  
  22.     srand(time(0));
  23.  
  24.     while(1)
  25.     {
  26.         Sleep(10);
  27.         AfxBeginThread(Func, NULL);
  28.         //Func(NULL);
  29.     }
  30.  
  31.     DeleteCriticalSection(&crtsec);
  32.     return nRetCode;
  33. }
  34.  
Oct 18 '07 #3
Banfa
9,065 Expert Mod 8TB
I did modify it by using critical sections, but still the same problem. I don't feel like writing my own rand function. Isn't there anyway to get this done?
Not really unless you have a separate thread which serves random numbers to the other threads so that only 1 thread is calling rand. This would be more complecated than writing your own rand function.

The critical sections are not working in this instance because they have no effect on the code they contain all they do is prevent 2 threads running the same bit of code at the same time which would be required if that bit of code was using some static data to prevent data corruptions by multiple accesses to that data.


Honestly writing your own rand function just isn't that hard and I suspect if you check the references I gave you will find the code or pseudo code for one without having to do much writing at all.
Oct 18 '07 #4
DumRat
93
So, I'll try my hand at a rand function of my own then. Thanks.
Oct 18 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
Why not take the random number from the last call and use it as an argument to your thread?

That way your thread could call srand() using the argument followed by
rand() to to get the next random number.
Oct 18 '07 #6
Banfa
9,065 Expert Mod 8TB
Why not take the random number from the last call and use it as an argument to your thread?

That way your thread could call srand() using the argument followed by
rand() to to get the next random number.
I don't think that would work in this case were a lot of threads are being started asynchonously.


EDIT: Actually I take this back it would with use of critical section.
Oct 18 '07 #7
weaknessforcats
9,208 Expert Mod 8TB
I don't think that would work in this case were a lot of threads are being started asynchonously.
In that case you could use a server thread to generate the random numbers. This thread would just idle out there looking in a mailbox for a random number request. It could out the random number inthe mailbox. All of the other threads just use the mailbox in a critical section.
Oct 18 '07 #8
Banfa
9,065 Expert Mod 8TB
In that case you could use a server thread to generate the random numbers. This thread would just idle out there looking in a mailbox for a random number request. It could out the random number inthe mailbox. All of the other threads just use the mailbox in a critical section.
You could do this, in fact I said so. But I think it is easier to write your own PRNG and put it in a critical section.
Oct 18 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Tom McCallum | last post by:
Can any tell me why rand() is such a bad pseudo-random number generator. In all the articles I have read they say that you can predict the outcome of rand() but when I used its output with NIST's...
7
by: eyal.susser | last post by:
I hear rand() is not thread safe. I was using it, foolish man that I am. But what is meant exactly by unsafe? What can happen? Bizzare results from rand()? Something worse? Thanks, Eyal.
36
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
8
by: Jack | last post by:
When I use rand(), is the RAND_MAX value how long I am guaranteed that the same value will not appear twice? And is this a floating window? For example, if RAND_MAX is 32767, and I make...
6
by: Roka | last post by:
Hi all. I'm reading a program which used the sentence below: #define NUM_THREADS 10 ... ... int rand_num; rand_num = 1+ (int) (9.0 * rand() / (RAND_MAX + 1.0)); sleep(rand_num); ... ......
4
by: Siam | last post by:
Hi all, I'm writing a shell language in c++ that supports the generation of random numbers, and by its nature, each command must be executed in a new thread. The call to the random function from...
5
by: ds | last post by:
Hi all, rand() is not thread safe, a fact that may not be so bad after all.. However, I face the following problem: a piece of code uses rand() to get a random sequence, but always seeds with...
10
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
15
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.