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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <thread>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <sys/types.h>
#include <linux/unistd.h>
#include <sys/syscall.h>

void *myThreadFun(void *vargp) {
    int arr[200];
    int CountForOdd;
    int CountForEven;
    srand (time(0));

//    for (int i = 0; i < 7; i++) {
//        CountForOdd = 0;
//        CountForEven = 0;
//        arr[200] = 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[7];

       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
Registered users can post here. Sign in or register to post.