pthreads的一些坑 作者: LiesAuer 时间: 2018-01-20 分类: 开发 整理总结了一些自己在使用pthreads时遇到的坑,不定期更新。 Env: php version: 7.0.19 pthreads version: 3.1.6 :warning:FBI WARNING 除特殊注明,本文内所有多线程相关代码的结果输出顺序都将会受线程执行顺序影响而不定,如您在实际当中发现您的结果顺序(结果一样,只是顺序错乱)和本文不一致,请保持淡定,都坐下,基本操作,基本操作。  - [(new class extends \Thread {})->start()将导致代码阻塞](/blog/post/pthreads_trap.html#trap01 "(new class extends \Thread {})->start()将导致代码阻塞") - [函数中创建线程将导致函数阻塞](/blog/post/pthreads_trap.html#trap02 "(函数中创建线程将导致函数阻塞") - [Pool非继承于Threaded](/blog/post/pthreads_trap.html#trap03 "Pool非继承于Threaded") [线程中无法进行哈希表操作以及使用不可序列化的对象](/blog/post/pthreads_trap.html#trap04 "线程中无法进行哈希表操作以及使用不可序列化的对象") ## (new class extends \Thread {})->start()将导致代码阻塞 ### 代码复现 ```php (new class extends \Thread { public function run() { echo "i am new thread\n"; $this->wait(); } })->start(); echo "i am main thread\n"; ``` ### 期待结果 ``` i am new thread i am main thread ``` ### 实际结果 ``` i am new thread ``` ### 解决方案 不使用(new class extends \Thread {})->start()语法 ```php $t = new class extends \Thread { public function run() { echo "i am new thread\n"; $this->wait(); } }; $t->start(); echo "i am main thread\n"; ``` ### 最终结果 ``` i am new thread i am main thread ``` ## 函数中创建线程将导致函数阻塞 ### 代码复现 ```php function my_function() { $t = new class extends \Thread { public function run() { echo "i am new thread inside function\n"; $this->wait(); } }; $t->start(); } my_function(); echo "i am main thread\n"; ``` ### 期待结果 ``` i am new thread inside function i am main thread ``` ### 实际结果 ``` i am new thread inside function ``` ### 解决方案 暂无,不确定是否为BUG。 ## Pool非继承于Threaded Pool 是标准的 PHP 对象,它并没有继承 Threaded 类,所以不可以在多个线程上下文中共享同一个 Pool 对象。 ## 线程中无法进行哈希表操作以及使用不可序列化的对象 以下操作素不行滴: ```php $this->arr['element'] = 'ng'; // 应改为以下形式 $this->arr = ['element'=>'ok']; $this->callback = function(){}; ``` 标签: none