I am working in some code trying to make it use threads, with little success. The code is as follows (using some online tuts)
(1) Create an array to save arguments to pass to each thread.
(2) The struct where thread args are stored
(3) Function each thread executes
(4) Main, where I create each pthread and pass args. end and begin are dummy i and i+1 just for testing purposes.
#include <pthread.h>
struct thread_data* thread_data_array;
struct thread_data{
int thread_id;
int begin;
int end;
};
void *proccessData(void *threadarg)
{
struct thread_data *my_data = (struct thread_data *) threadarg;
int id = my_data->thread_id;
int start = my_data->begin;
int end = my_data->end;
printf("%s%d%s%d%s%d%s","Process: Id ",id," begin: ",start," end: ",end,"\n");
// Init
FILE* fileOut;
// do stuff
fileOut = fopen(someNameUsingId, "w");
// more stuff
fclose(fileOut);
}
int main(int argc, char **argv)
{
int n_th = atoi(argv[1]);
thread_data_array = malloc(n_th*sizeof(struct thread_data));
pthread_t threads[n_th];
int i;
for (i=0; i<n_th; i++)
{
thread_data_array[i].thread_id = i;
thread_data_array[i].begin = i;
thread_data_array[i].end = i+1;
pthread_create(&threads[i], NULL, proccessData,(void *) &thread_data_array[i]);
}
}
What I am getting: Sometimes nothing is printed, Sometimes some ids are printed twice. Files are not created (one in every 5 lets say, files are created, and are empty)
But using this in main works as I am expecting, id 1 from 0 to 1 is printed, id 2 from 1 to 2, and both files are created and have the right content
thread_data_array[0].thread_id = 1;
thread_data_array[0].begin = 0;
thread_data_array[0].end = 1;
proccessData((void *) &thread_data_array[0]);
thread_data_array[1].thread_id = 2;
thread_data_array[1].begin = 1;
thread_data_array[1].end = 2;
proccessData((void *) &thread_data_array[1]);
Can someone point out what am I doing wrong, and how to solve it?
Thanks in advance
mainis ending before threads do, but can't figure out how to solve itpthread_joinwill solve the issue, call it for each created thread in mainpthread_join()function is called to wait for the threads to complete. If main is done before threads are done, they will die before they finished their job