zoukankan      html  css  js  c++  java
  • php线程pthread实践

    php有线程吗?----有,但是需要扩展pthreads,扩展方式网上有一堆的教程,这是只做线程demo。

    file_put_contents(dirname(__FILE__).'/1.txt', '1111', FILE_APPEND);
    class test extends Thread {
        public function __construct($arg){
            $this->arg = $arg;
        }
        public function run(){
            file_put_contents(dirname(__FILE__).'/1.txt', '3333', FILE_APPEND);
            $getCreatorId = $this->getCreatorId();//创建当前线程的线程ID
            $getCurrentThreadId = Thread::getCurrentThreadId();//当前执行线程的ID
            $getThreadId = $this->getThreadId();//引用线程的ID
            if($this->arg){
                if ($this->arg=='World'){
                    sleep(3);
                }
                echo "Hello".$this->arg.'<br />
    getCreatorId:'.$getCreatorId.'创建当前线程的线程ID<br />
    getCurrentThreadId:'.$getCurrentThreadId.'当前执行线程的ID<br />
    getThreadId:'.$getThreadId.'引用线程的ID<br />';
            }
        }
    }
    $thread = new test("World");
    $thread->start();
    $thread->join();
    // var_dump($thread->isJoined());
    
    // $thread2 = new test("World2");
    // $thread2->start();
    // $thread2->join();
    file_put_contents(dirname(__FILE__).'/1.txt', '2222', FILE_APPEND);

    1.txt中保存的内容为:111133332222,若屏蔽$thread->join(),则1.txt的内容为111122223333。

    解析:整个程序的执行为主线程, $thread->start()的时候会自动执行Thread类的的run()方法,为子线程,子线程会在主线程执行完毕后执行(异步/非阻塞),若加上$thread->join(),则$thread->start()的时候会立即执行子线程,会影响主线程的后续执行(同步/阻塞)

     

    If the copyright belongs to the longfei, please indicate the source!!!
  • 相关阅读:
    ajax中文乱码问题的总结
    JQuery中$.ajax()方法参数详解
    Jquery的parent和parents(找到某一特定的祖先元素)
    div节点的操作(添加,删除,替换,克隆)
    js 刷新页面
    ADO.NET 体系结构
    数据访问技术介绍
    WebForm页面数据绑定总结
    sql 智能提示
    用TTTAttributedLabel创建变化丰富的UILabel
  • 原文地址:https://www.cnblogs.com/longfeiPHP/p/9632858.html
Copyright © 2011-2022 走看看