简体   繁体   English

线程输入函数和普通函数有什么区别?

[英]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* parameter)
{
   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". 使用pthreads,线程的所谓“启动例程”是一个函数,它使用单个void*参数并返回void* ,但是没有什么可以阻止您“正常”调用同一函数。

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: man pthread_create很好地定义了它:

http://linux.die.net/man/3/pthread_create 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM