473,799 Members | 2,985 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

rand() and threads

93 New Member
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 3793
Banfa
9,065 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
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 New Member
So, I'll try my hand at a rand function of my own then. Thanks.
Oct 18 '07 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
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 Recognized Expert Moderator Expert
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 Recognized Expert Moderator Expert
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 Recognized Expert Moderator Expert
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
4225
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 random number testsuite it passed all of the tests thrown at it for randomness. Can anyone suggest a test I could use that it would fail? A pointer to a suitable article would be appreciated. Thanks for your help in advance, Tom
7
7372
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
2696
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
4395
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 500,000 consecutive rand calls then is the rand() algorithm going to guarantee me that no floating window of calls over that 500,000 rand calls will have the same value twice? The only way that would work is if the series was identical everytime.
6
2607
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); ... ... (The program is long so I used a part of it.)
4
2798
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 my language simply propogates up to the rand( ) function from c++. For some reason, C++ will give each thread independent use of their own rand( ) function, so that a rand( ) call from one thread won't affect another thread's call to rand( )....
5
2325
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 the same seed for reproducibility of the results. Now I am porting this (old C89) code and have setup a nice app with threads that drives on one thread the old code and on another the new code, so that I can compare the results and see that nothing...
10
3022
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
3948
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 of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9540
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9068
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
7564
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
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.