关于多线程:pthread_create函数格式和指针-C Linux POSIX库

pthread_create function format and pointers - C Linux POSIX library

我的问题是,就指针等而言,pthread_create函数及其调用的函数的格式到底是什么?尽管需要澄清我在该领域的知识,但是我可以将注意力集中在变量指针上,但是函数指针会变得很糟糕。

我了解首选格式是

1
2
3
4
5
6
7
8
void *threadfunc(void *arg);

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

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

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

1
2
3
void threadfunc(void *arg);

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

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

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


转到"源"-POSIX标准。对于pthread_create(),它表示:

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

也就是说,您的" start_routine"必须是一个返回void *并接受void *自变量的函数。

1
2
3
4
5
6
void *possible_thread_start_routine(void *data)
{
    SomeStruct *info = data;
    ...main code for thread...
    return 0;
}

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


您尚未提供void *threadfunc(void *arg);的版本,但我猜测其中没有return语句。这就是编译器警告您的原因。由于声明说它必须返回void*,因此您应该返回void*void*是指向任何指针类型的指针。只有void(不带星号)不需要return语句,因为它不返回任何内容。

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


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

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