#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
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));
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.