### rand() array I have 7 arrays and 7 threads. I get 7 ID for all threads. ID are different but arrays have the same values. Why?

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647`` ``````#include #include #include #include #include #include #include #include #include void *myThreadFun(void *vargp) { int arr; int CountForOdd; int CountForEven; srand (time(0)); // for (int i = 0; i < 7; i++) { // CountForOdd = 0; // CountForEven = 0; // arr = 0+rand()%10; for(int i=0; i<199; i++) { arr[i] = 0+rand()%10; if(arr[i]%2==0) CountForEven++; if(arr[i]%2==1) CountForOdd++; } // } std::cout << "In array there are " << CountForEven << " even number and " << CountForOdd << " odd number"<< std::endl; CountForOdd = 0; CountForEven = 0; pid_t id = {(pid_t) syscall (SYS_gettid)}; std::cout << "tid " << id << std::endl; return 0; } int main() { pthread_t tid; for(int i{0}; i<7; i++){ pthread_create(&tid[i], NULL, myThreadFun, NULL); pthread_join(tid[i], NULL); } exit(0); } ``````

 ``` In array there are 96 even number and 103 odd number tid 2348 In array there are 96 even number and 103 odd number tid 2349 In array there are 96 even number and 103 odd number tid 2350 In array there are 96 even number and 103 odd number tid 2351 In array there are 96 even number and 103 odd number tid 2352 In array there are 96 even number and 103 odd number tid 2353 In array there are 96 even number and 103 odd number tid 2354 ```
Last edited on You seeded on the basis of time. This would be (near enough) the same on all threads, so their sequence of random numbers all started at the same point. You seeded on the basis of time. This would be (near enough) the same on all threads, so their sequence of random numbers all started at the same point.

`I solved it with the help of std::this_thread::sleep_for (std::chrono::seconds(1));`
Last edited on If you don't want unnecessary sleeping, also consider rand_r which can be thread-safe (give each thread a different seed) https://linux.die.net/man/3/rand_r or in C++11 use something like a thread_local std::mt19937 generator.
Last edited on
Topic archived. No new replies allowed.