I have a problem with pthread_create. In this test, I create an array of integers, and then try to use them as parameters for a function that must be executed into a thread.
This is where I create the indexes:
int *indexes = (int *) malloc(sizeof(int)*threadNumber);
int i;
for (i = 0; i < threadNumber; i++){
indexes[i] = i;
}
And this is where I create threads:
int i;
for (i = 0; i < threadNumber; i++){
printf("%i %i ", i, indexes[i]);
}
for (i = 0; i < threadNumber; i++){
printf("%i %i ", i, indexes[i]);
pthread_create(sons + sizeof(pthread_t)*i, NULL, sonSimulation, (void *) &indexes[i]);
}
The first printf prints the following:
0 0 1 1 2 2 3 3 4 4
The second one, which is supposed to print the same output, prints this:
0 0 1 1 2 2 3 3 4 23154684
The last number changes each time I executes the code. I'm not able to fix this. Any suggestion?
(sonSimulation just prints the parameter)
sons? How is it declared? Why don't you use plain array indexing for it? Also, you're threads doesn't overwrite the pointer they get?sons[i]orsons + iinstead ofsons + sizeof(pthread_t)*i. Also, please post thesonSimulationfunction.malloc()and family inC.