I'm trying to write and run a PHP extension that spins off a pthread (using the POSIX library in C) which detaches and runs forever (it reads messages from a queue, but for the purposes of this question that isn't important, and I'm just trying to get it to spin off a function that just detaches and returns for proof of concept).
To clarify: This is not using the pthreads extension in php, but using the POSIX pthreads library in a custom php extension. I've confirmed that the environment can compile and execute C code that uses the POSIX pthreads library.
The function that spins off the thread is:
static int init_thread()
{
int ret = 0;
pthread_t thread;
ret = pthread_create(&thread, NULL, threadFunc, NULL);
if (ret != 0)
{
fprintf(stderr, "pthread_create failed with error code %d\n", ret);
return -1;
}
return 0;
}
But this seems to stop any of the extension from executing.
Note
: I've also tried using a php extension global variable pthread_t instead of instantiating a pthread_t in init_thread
but to the same results...
This function is called in RINIT and is only called the very first time a PHP worker process starts, not every request (I've confirmed this separately). For debugging I've tested all this with threadFunc
simply detaching and returning with pthread_detach(pthread_self());
and return 0;
.
I've confirmed that the extension is set up properly and works without the pthread_create
line by printing to log files from MINIT, GINIT, and even in RINIT.
However, whenever the ret = pthread_create(&thread, NULL, threadFunc, NULL);
line in init_thread
is uncommented, it seems like nothing in the extension runs.
For example, MINIT supposedly runs before any time RINIT runs, and I create and write to a file to confirm that MINIT is running (I use this file as "proof" that the extension is executing code as I expect). However, when the pthread_create
line is uncommented, that file that MINIT creates is never even made or written too, even though MINIT should run before that pthread_create
is ever reached.
There's no clear error in the nginx or php7.4 log files, and the site works normally even when the extension seems to be broken.
I'm really at my wits end with why this isn't working, as my use of pthread_create is just to spin off a function that detaches and returns. Building with ZTS
shouldn't even be required since the thread doesn't interact with PHP at all (Just in case, I've also tried defining ZTS
and COMPILE_DL_EXTNAME
to run ZEND_TSRMLS_CACHE_DEFINE
but to no avail).
I'm running all this with php7.4, and am building the extension as a .so file with phpize
, ./configure
, and make
, then placing the .so file appropriately and adding the extension=EXTENSION_NAME
in /etc/php/7.4/fpm/php.ini
.
Any and all ideas are greatly appreciated!