【问题标题】:How do I call a function that returns a void pointer?如何调用返回空指针的函数?
【发布时间】:2016-06-30 12:37:11
【问题描述】:

我的这段代码如下所示。

其中 nrthr 代表线程数,由用户输入。我总是希望我的“主程序”调用 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)
{
    ...
}

【问题讨论】:

  • void* pin, *pout; pout = testFunc(pin); 之类的有什么问题?
  • 是什么阻止您将其作为普通函数调用 void *ret = testFunc(somedata/NULL)?
  • 我想我应该这样做,我只是想我可以在不创建变量的情况下调用它,因为该函数不返回任何内容。
  • @Fjodor,当然,如果你不关心返回值,你不需要将它存储在一个变量中,你可以调用你的函数:testFunc(NULL),或者其他您要传递给函数的值

标签: c void-pointers


【解决方案1】:

如果testFunc 应该在单独的线程上运行,那么可能它不会简单地做某事并返回。

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

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

【讨论】:

    【解决方案2】:

    您可以像这样拨打testFunc

    void *result = testFunc(args);
    

    但是,如果testFunc 调用任何与pthread 相关的函数,请注意。由于在这种情况下,函数没有在单独的线程中运行,因此调用 pthread_exit 之类的函数将无法正常工作。

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2021-01-20
      • 2021-03-23
      相关资源
      最近更新 更多