Iam new to c programming and needs some help.
long *taskids[NUM_THREADS];
for(t=0; t<NUM_THREADS; t++)
{
taskids[t] = (long *) malloc(sizeof(long));
*taskids[t] = t;
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]);
...
}
This code fragment demonstrates how to pass a simple integer to each thread. The calling thread uses a unique data structure for each thread, insuring that each thread’s argument remains intact throughout the program. Iam not able to understand how this is happening can somebody explain it??
What this code is doing is storing an array of pointers to allocated data. Each thread has space allocated for a long and is then passed a pointer to that value. This gives the thread a place to work that the main thread still has access to.
This could be done with a little less allocation:
Though this does decrease the flexibility for freeing the taskids. It also requires that this function doesn’t return until all the threads have finished.