如何调用 returns 空指针的函数?

How do I call a function that returns a void pointer?

我有下面显示的这段代码。

其中nrthr代表线程数,由用户输入。我总是希望我的 "main program" 调用 testFunc 一次,所以如果用户输入 nrthr 为数字 3,那么我想创建 2 个新线程。所以我的问题是...我怎样才能在 while 循环之前调用 testFunc?

int threadCount = 0;
...

// Call testFunc here

while(threadCount < nrthr - 1) {
        fprintf(stderr, "Created thread: %d\n", threadCount);
        if(pthread_create(&(tid[threadCount++]), NULL, testFunc, args) != 0)
            fprintf(stderr, "Can't create thread\n");
}

void *testFunc(void *arg)
{
    ...
}

您可以这样调用testFunc

void *result = testFunc(args);

但是,如果 testFunc 调用任何与 pthread 相关的函数,请注意。由于在这种情况下,该函数不在单独的线程中 运行,因此调用 pthread_exit 之类的函数将不会像您预期的那样工作。

如果 testFunc 应该 运行 在一个单独的线程上,那么它 可能 它不只是做某事并且 return.

如果该假设成立,您不能简单地在循环之前调用它,否则您的主线程将无法同时创建其他线程 运行 .

如果该假设为假,那么您可以像调用任何其他函数一样简单地调用它,testFunc(args),如果您不关心它,则忽略 return 值。另一件需要注意的事情是 pthread_exit 从主线程调用时的行为 - 请参阅 Is it OK to call pthread_exit from main?.