gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:11:04 25 4
gpt4 key购买 nike

我正在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com