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

My c++ library create a thread with pthread_create somewhere in the code. Using my library inside a stand-alone application works great, but when using it in PHP extension. The function never returns.

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

The "B" is never printed.

How can I do this?

Thanks!

You have a race condition between the newly-created thread printing and the process terminating. You need some kind of synchronization, such as joining the thread before allowing the process to terminate. (Using sleep is okay to demonstrate the problem, but never use sleep as a form of thread synchronization.)

Try something like this:

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

where I have taken your code, added some simple error handling, and joined the produced thread to make sure it has finished.

I used some C++11 features above (auto and nullptr in particular), if they aren't supported by your compiler it should be pretty easy to replace them (what is the return value type of your pthread_create?)