PHP多线程(pthreads)参数传递学习笔记
PHP多线程编程中可以通过Thread,Worker的构造方法传递变量到线程,也可以通过线程的public属性或public方法实现,经研究发现都是通过serialize()和unserialize()实现传递,这样就会造成几个问题:
1.性能问题
2.PDO等某些类型不能serialize所以就不能传递到线程,这两个问题是能通过其他凡是解决的,解决方法仁者见仁智者见智.
另外.可以通过传递匿名函数到线程中.但是有个bug.匿名函数不能赋值给线程中的属性.导致传递的匿名函数只能在线程的构造方法中才能使用(call_user_fun*系列函数调用).
Thread属性定义一定要注意必须在构造方法中初始化,否则必定为null,__construct()和run()里面的代码不在一个次元,如果属性不是PHP标量在run()中不能修改,例如构造方法中初始化一个对象,然后run()中修改对象属性不会生效.
正确写法如下:
abstract class Task extends Thread { private $finished ; public $terminated ; protected $id ; public $terminate ; public function __construct( $id ) { $this ->id = $id ; $this ->terminated = true; $this ->finished = false; $this ->terminate = false; } }错误写法如下:
abstract class Task extends Thread { private $finished =false; public $terminated =false; protected $id ; // HdhCmsTestphpfensi测试数据 public $terminate =false; public function __construct( $id ) { $this ->id = $id ; } }这样也是错的,无论stdClass还是数组,代码如下:
abstract class Task extends Thread { private $info ; public function __construct( $task ) { $this ->info = array (); $this ->info [ 'task' ] = $task ; $this ->info [ 'finished' ] = false; $this ->info [ 'terminate' ] = false; $this ->info [ 'terminated' ] = false; $this ->info [ 'error' ] = false; $this ->info [ 'info' ] = array (); } }后来研究又发现,复合类型的数据整体赋值貌似能起作用,如果程序有很多回调函数在线程内部用的话就是找死啊.
查看更多关于PHP多线程(pthreads)参数传递学习笔记 - php高级应用的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did30162