在 C 中使用 pthread 调用 php 函数


Calling php functions using pthread in C

我需要多线程一个php函数,但是当我调用php函数时,我收到此错误"Safari无法打开页面" Safari can’t open the page “‎localhost/home.php” because the server unexpectedly dropped the connection. This sometimes occurs when the server is busy. Wait for a few minutes, and then try again.

我的 php 文件中有这些行

<?php
echo "Hello World","<br>";
open_thread("hello");
function hello() {
     echo "Hello World";
}

当我从open_thread("hello");中删除hello时,它只是输出以下警告: Warning: open_thread() expects exactly 1 parameter, 0 given in /Users/username/Sites/home.php on line 3

当我调用包含输出的 C 函数时,当我从函数服务器中删除输出并且不显示任何内容时,也会发生这种情况。

问题发生在这里pthread_join(tid, NULL);

这是我的 C 代码

PHP_FUNCTION(open_thread)
{
    zval *threaded_func;
    zend_string *func_name;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &threaded_func) != SUCCESS) {
        return;
    }

    if (Z_TYPE_P(threaded_func) != IS_NULL) 
    {
        if (!zend_is_callable(threaded_func, 0, &func_name TSRMLS_CC)) 
        {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "’%s’ is not a valid read callback", func_name);
            efree(func_name);
            RETURN_FALSE;
        }
        efree(func_name);
    }

    pthread_t tid;
    zend_printf("Starting..'n");
    pthread_create(&tid, NULL, (void *) threaded_func, NULL);
    pthread_join(tid, NULL);
    zend_printf("Finished'n");
}

问题
这是线程安全问题吗?我该如何解决?

PHP可以构建为支持多线程SAPI - ZTS模式 - 但是,重要的是要意识到使用的内存模型不共享任何内容。

在无共享模型中,每个线程都有不同的解释器(编译器、执行器、所有模块全局变量、所有用户代码、整个批次)。

这意味着各种事情:

  • 为线程 A 编译的代码不能由线程 B 执行。线程 B 必须从线程 A 复制代码,执行类似 pass_two 的操作并执行代码的副本。
  • 从线程 A 复制的引用对象、资源或哈希表的代码可能会(将)在没有适当准备和/或适当对象处理程序的情况下中断。

简单地启动一个线程并尝试调用Zend注定要失败,因为它忽略了PHP的共享无本质。

新线程的流程需要如下所示:

void routine(void *thing) {
    ts_resource(0);
    php_request_startup();
    /* do stuff */
    php_request_shutdown();
    ts_free_thread();
}
  • ts_resource:这会在新线程中初始化 TSRM,进而初始化一些 Zend
  • php_request_startup :初始化其余所有内容,其中包括为所有模块运行RINIT
  • php_request_shutdown:这运行RSHUTDOWN,一般清理
  • ts_free_thread:可选免费,否则会在进程关闭时发生(当 TSRM 最终关闭时)
实际上,如果示例流

尝试调用由(为)另一个线程编译的用户代码,则示例流也会失败:在请求启动之后,在调用用户代码之前,您需要先将代码复制到当前上下文中。

这些在

现实世界中如何工作的细节可以在 pthreads 扩展源中找到。