php多线程变量范围共享问题

标签 php multithreading variables object pecl

我正在用 php 制作一个多线程 cli 应用程序,但在线程之间的变量共享方面遇到了一些问题

这是我的代码:

<?php
class testThread extends Thread{
    public function run(){
        wrapper::hello();
    }
}

class wrapper{
    public static $test0;
    public static $test1;
    public static function create(){
        self::$test0 = 'a string';
        self::$test1 = new DateTime();

        echo '#main thread echo start' . "\n";
        var_dump(self::$test0);
        var_dump(self::$test1);
        echo '#main thread echo end' . "\n\n";
        //echo '#---------------------------' . "\n\n";

        $test = new testThread();
        $test->start();
    }

    public static function hello(){
        echo '#sub thread echo start' . "\n\n";
        var_dump(self::$test0);
        var_dump(self::$test1);
        echo '#sub thread echo end' . "\n";
    }
}

wrapper::create();
?>

结果

#main thread echo start
string(8) "a string"
object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2013-10-14 12:36:17"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(11) "Asia/Taipei"
}
#main thread echo end

#sub thread echo start

string(8) "a string"
NULL
#sub thread echo end

在这个结果中,可以看到静态String变量可以从子Thread中获取值,但是DateTime对象不行!

我的php版本是

PHP 5.5.4 (cli) (built: Oct 9 2013 11:27:32) (DEBUG) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies

如果您有任何意见,请在这里留下,这对我很有帮助。

谢谢。

--------更新------------

这是我的 phpinfo

php test.php | grep "Confi"
Configure Command =>  './configure'  '--enable-sockets' '--enable-debug' '--enable-maintainer-zts' '--enable-pthreads'
Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini
Configuration

最佳答案

摘自PHP手册中的介绍

Static Members: When a new context is created ( Thread or Worker ), only the simple members of static classes are copied, no resources or objects are copied into the threading context from static class members. This allows them to function as a kind of thread local storage. For example, upon starting the context, a class whose static members include connection information for a database server, and the connection itself, will only have the simple connection information copied, not the connection. Allowing the new context to initiate a connection in the same way as the context that created it, storing the connection in the same place without affecting the original context.

http://php.net/manual/en/intro.pthreads.php

关于php多线程变量范围共享问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19353659/

相关文章:

循环内的 Javascript 变量声明

arrays - 是否可以在 Perl foreach 循环中分配两个变量?

javascript - 我如何在 javascript mailto 中附加多个文档?

javascript - 如何将数字加载到 MySQLi fetch_array() 函数中

Java 图形用户界面和线程

python - 并行化一个让两个玩家相互对抗的 Python for 循环(博弈论模拟)

java - 线程中断状态被清除——可能是 Java 错误

php - 使用 woocommerce : get_gallery_attachment_ids() thumbs not showing 移动 wordpress

php - 使 PHP 回显 <a href= link>

javascript - 从函数内部返回变量到外部