开发者

What is the difference between a thread entry function and a normal function?

I would like to know the difference between a thread entry function:

void* thread_function (void* para开发者_如何学JAVAmeter)
{
   struct parameter * thread_data = (struct parameter *)parameter;
   char buffer[20];
   int temp;
   printf_buffer(buffer);
}

and a normal function:

void printf_buffer(char *buffer)
{
    printf("buffer is %s",buffer);
    return;
}

I know a thread entry is called when a thread is created, and how normal functions are used.

Are there any other differences between thread entry functions and a normal functions in terms of execution , behavior, or creating instances?


There is no difference in the language between what you call a "thread function" (although Justin has edited to call it a "thread entry function") and what you call a "normal function".

With pthreads, the so-called "start routine" of a thread is a function that takes a single void* parameter and returns void*, but there's nothing to stop you calling the same function "normally".

When the start routine of a thread returns, the thread finishes execution, but that's just because the threading implementation calls it, and then finishes the thread. It's not because of anything special to do with the start routine itself.


A thread function is just the entry/exit point of a thread. The execution of that function is no different from what you refer to as a normal function.


man pthread_create defines it quite well:

http://linux.die.net/man/3/pthread_create

one major difference that has not been mentioned yet is that the thread entry should expect to operate on a stack other than the caller's. for this reason, you will often want to pass heap copies of resources as your argument when your thread is detached, then free it in the entry:

// the caller must pass a heap copy of struct parameter* arg
void* detached_entry(void* arg) {

  struct parameter* parameter = (struct parameter*)arg;
  ...
  free(parameter);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜