C++ problem random

02/13/2013 18:41 Kingrap#1
Hi community,
i have a small problem with the random function in the thread!

Code:
int rand_func()
{
    srand((unsigned int)time(NULL));
    int output = rand()%3;
    return output;
}

void test(void *id)
{
   int n = rand_func();
}
i opened two threads with _beginthread() but n of first thread is equal to n of second thread :confused:..

help me please, i need a random number from 0 to 3..
the second n should not be equal to the first n!

if possible I would like to know the reason ;)

sorry for my english *-*
02/13/2013 18:48 Schlüsselbein#2
You should call srand only once (for instance in your main routine).
02/13/2013 18:52 Raz9r#3
Quote:
Originally Posted by Schlüsselbein View Post
You should call srand only once (for instance in your main-routine).
Also, this is rather C than C++. Note that there exists no language named "C/C++" for a reason.
What about the headers <random> and, not to forget, <thread>?
02/13/2013 20:41 MrSm!th#4
Btw. did you try the code more than once? That range is rather small, it could be just an accident that both threads got the same result.
02/13/2013 22:58 Kingrap#5
i have solved the problem thank ;)
02/13/2013 23:38 Schlüsselbein#6
Quote:
Btw. did you try the code more than once? That range is rather small, it could be just an accident that both threads got the same result.
I dont think so.
For example:
Code:
#include <iostream>
#include <ctime>
#include <vector>

int main()
{
	const unsigned int length = 500000;

	std::vector<unsigned int> v;
	v.reserve(length);

	for(int i = 0; i < length; ++i)
		v.push_back(static_cast<unsigned int>(::time(NULL)));

	std::cout << "Element 0: \t" << v.front() << std::endl;
	std::cout << "Element " << length << ": \t" << v.back() << std::endl;
}
For me with my rather slow pc (1,9ghz Dual Core processor) i need up to 500k iterations in debug mode before i get t0 + 1 second.
Therefore he seeds the random number generator with the same seed -> same result.
03/03/2013 23:58 jomergallano#7
you can have some other codes
here :
[Only registered and activated users can see links. Click Here To Register...]