I am beginner in multi thread programming. I have a homework, which I should create some number of thread (in my case 10) and generate a random number inside of each one. when I debug my code (or put 'sleep(1)' command) it works correctly, otherwise the generated values are not equal anymore. please help me and explain me if you think there is something which I still did'nt understand it. The code:
#include<stdio.h>
#include<pthread.h>
#include<time.h>
int rn, sharedArray[10];
pthread_mutex_t lock;
int randomgenerator(){
//sleep(1);
srand(time(NULL)); // The value of random depend on the time with some changes in the time library
int rn, MAX = 10; // between 0 and 10
rn = rand()%MAX;
return rn;
}
void *rgen(void *arg){
int order = (int*)arg;
//pthread_mutex_lock(&lock);
int rn = randomgenerator();
printf("%d,%d\n", order,rn); //not working without printf why????
sharedArray[order]= rn;
//pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
void main(int argc, char *argv[]){
pthread_mutex_init(&lock, NULL);
pthread_t th[10];
int i;
for (i = 0; i <10; i ++){
pthread_create(&(th[i]), 0, rgen, (void *)i);
pthread_join(th[i], NULL);
}
int j, result = 0;
for (j=0; j<10; j++){
result = sharedArray[j] + result;
}
printf("the final result is: %d\n",result);
pthread_exit(NULL);
pthread_mutex_destroy(&lock);
}
And the output is:
0,3
1,3
2,3
3,3
4,3
5,3
6,3
7,3
8,3
9,3
the final result is: 30
The output which I expect with uncommenting the sleep is:
0,7
1,4
2,1
3,8
4,5
5,2
6,9
7,6
8,3
9,0
the final result is: 45