posix pthreads in c
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 unders开发者_如何学JAVAtand how this is happening can somebody explain it??
malloc
allocates enough memory to hold a long integer. It returns a pointer to long, along*
.- This
long*
is stored intotaskids[t]
so that it can be used later. pthread_create
is called. One of its arguments is a value to be passed to the new thread.- Since the
pthread_create
function does not know what kind of value the programmer wants to pass, it uses avoid*
which can be a pointer to anything.taskids[t]
is the pointer to a long integer. It is cast (that is the(void *)
) to a void pointer and given as an argument topthread_create
.
- Since the
pthread_create
creates a new thread and calls thePrintHello
function and passes the void pointer totaskids[t]
as the value toPrintHello
.- Once
PrintHello
starts, it will cast the void pointer back to a long pointer and then it can access the long integer that contains its taskid.
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:
long taskids[NUM_THREADS];
for(t=0; t<NUM_THREADS; t++)
{
taskids[t] = t;
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &taskids[t]);
...
}
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.
精彩评论