【问题标题】:pthread_create function format and pointers - C Linux POSIX librarypthread_create 函数格式和指针 - C Linux POSIX 库
【发布时间】:2011-12-15 20:36:52
【问题描述】:

我的问题是,就指针等而言,pthread_create 函数及其调用的函数的格式究竟是什么?尽管我需要澄清我在该领域的知识,但我可以围绕变量指针转头,但函数指针会变得很糟糕。

我了解首选格式是

void *threadfunc(void *arg);

int main()
{
    pthread_t threadinfo;
    int samplearg;
    pthread_create(&threadinfo, NULL, threadfunc, &samplearg);
}

但是,这会生成一个编译器警告,提示 threadfunc 没有返回值,所以显然 * 是关于 threadfunc 返回的内容,而不是函数的特征?

我还看到定义为的函数和 pthread_create 的格式如下:

void threadfunc(void *arg);

pthread_create(&threadinfo, NULL, (void *)threadfunc, &samplearg);

这两个中哪一个是正确的,或者它们在功能上是等价的?有人可以向我解释一下函数指针的机制吗?

最后一个问题,在生成多个线程的 for 循环中,为线程唯一值初始化 int samplearg 然后将其传递给 pthread_create(...) 是否可行?我知道samplearg 将在threadfunc 的范围内,我只是在检查以防C 不遵循典型的范围规则——因为samplearg 是在for() 循环内创建的,并且通常会退出for() 循环迭代后的范围,并且实际变量本身被传递而不是值。我会测试自己,但可能有一点你可以启发我,在远程 linux 机器上开发对我来说有点麻烦。

【问题讨论】:

  • pthread_create( ) 返回一个 int。来自手册页:返回值 如果成功,pthread_create() 函数将返回零;否则,将返回错误号以指示错误。
  • @PeteWilson - 他不是在谈论pthread_create()的返回值
  • @Brian Roach——所以他不是!谢谢你的接送。

标签: c multithreading pointers pthreads function-pointers


【解决方案1】:

转到“源”——POSIX 标准。对于pthread_create(),它说:

int pthread_create(pthread_t *restrict thread,
   const pthread_attr_t *restrict attr,
   void *(*start_routine)(void*), void *restrict arg);

也就是说,您的“启动例程”必须是一个返回 void * 并接受 void * 参数的函数。

void *possible_thread_start_routine(void *data)
{
    SomeStruct *info = data;
    ...main code for thread...
    return 0;
}

传递给线程启动例程的参数是argpthread_create() 中指定的参数。

【讨论】:

  • start_routine 周围括号内的指针表示什么? IE。 (*start_routine)
【解决方案2】:

您还没有给出void *threadfunc(void *arg); 的版本,但我猜其中没有返回语句。这就是编译器警告您的原因。由于声明说它必须返回一个void*,你应该返回一个void*void* 是指向任何指针类型的指针。只有void(没有星号)不需要return 语句,因为它什么都不返回。

顺便说一句,当另一个线程加入您当前正在启动的线程时,返回值将传递给pthread_join 语句。

【讨论】:

  • 是的,我没有返回值,因为我将 void *threadfunc(void *arg); 误解为具有 void 返回值和 * 指示的特殊属性的函数。合适的“空白”return 是什么?还是应该 return 是别的东西?当然 pthread_exit() 会在 threadfunc() 本身中被调用。
  • 如果没有什么要返回到加入线程,就返回NULL。
  • 我想我现在明白了指向 void 返回的指针的目的——它传递一个变量,然后将被强制转换,类似于传递输入 arg 的方式,对吧?
【解决方案3】:

传递给pthread_create() 的函数应该返回一个指向线程退出状态的空指针。

当您在线程退出后调用pthread_join()(通过返回或显式调用pthread_exit())时,您可以使用该返回值

【讨论】:

  • 那么你是说第一个公式,函数定义void *threadfunc(void *arg);是正确的?将指针返回到 void 的目的是什么?是否能够使用从pthread_join() 检索到的指针重新进入函数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多