繁体   English   中英

PHP扩展(在C ++中)中的pthread_create函数从不返回

[英]pthread_create in PHP extension (in C++) function never returns

我的c ++库在代码中的某个位置使用pthread_create创建了一个线程。 在独立应用程序中使用我的库效果很好,但是在PHP扩展中使用它时。 该函数永不返回。

void* threadloop(void * param)
{
    zend_printf("B\n");
}
PHP_FUNCTION(create_thread)
{
    pthread_t othread;
    pthread_create (&othread, NULL, threadloop, NULL);
    zend_printf("A\n");
}

永远不会打印“ B”。

我怎样才能做到这一点?

谢谢!

在新创建的线程打印和进程终止之间存在竞争条件。 您需要某种同步,例如在允许进程终止之前加入线程。 (可以使用sleep来演示该问题,但切勿将sleep用作线程同步的一种形式。)

尝试这样的事情:

void* threadloop(void * param)
{
  zend_printf("B\n");
}
PHP_FUNCTION(create_thread)
{
  pthread_t othread;
  auto result = pthread_create (&othread, NULL, threadloop, NULL);
  if (result != 0)
    zend_printf("Error!\n");
  zend_printf("A\n");
  void* result = nullptr;
  auto result2 = pthread_join( othread, &result );
  if (result2 != 0)
    zend_printf("Error2!\n");
}

我在这里获取了您的代码,添加了一些简单的错误处理,并加入了产生的线程以确保其已完成。

我在上面使用了一些C ++ 11功能(特别是autonullptr ),如果编译器不支持它们,则替换它们应该很容易( pthread_create的返回值类型是什么?)

暂无
暂无

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

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