开发者

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, a long*.
  • This long* is stored into taskids[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 a void* 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 to pthread_create.
  • pthread_create creates a new thread and calls the PrintHello function and passes the void pointer to taskids[t] as the value to PrintHello.
  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜