畫江湖之 PHP 多執行緒開發 【利用多執行緒 序列任務變並行處理 從而減少序列執行時間】

Krisji發表於2019-04-05
<?php

// 繼承 Thread 的類具有建立執行緒的能力
class Request extends Thread
{
    private $sql;

    private $dsn;

    public function __construct($sql, $dsn)
    {
        $this->sql = $sql;
        $this->dsn = $dsn;
    }

    public function run()
    {
        $db = new PDO($this->dsn);

        $stat1 = $db->query($this->sql);

        $result = $stat1->fetchAll(PDO::FETCH_ASSOC);

        print_r($result);
    }
}

$dsn = 'sqlite:/tmp/pselect.db';
$db = new PDO($dsn);

$db->exec('create table users(id int, name varchar(255))');
$db->exec('create table books(id int, name varchar(255))');

//$db->exec("insert into users(id, name) values(1, '張三')");
//$db->exec("insert into users(id, name) values(2, '李四')");

//$db->exec("insert into books(id, name) values(1, '三國')");
//$db->exec("insert into books(id, name) values(2, '水滸')");

$sql = [
    'select * from users',
    'select * from books',
];

//$stat1 = $db->query($sql[0]);
//$stat2 = $db->query($sql[1]);

//$results1 = $stat1->fetchAll(PDO::FETCH_ASSOC);
//$results2 = $stat2->fetchAll(PDO::FETCH_ASSOC);

//print_r($results1);
//print_r($results2);

$arr = [];
for ($i = 0; $i < 2; $i++) {
    $request = new Request($sql[$i], $dsn);
    $arr[$i] = $request;
    // 建立新執行緒,隨後執行緒會執行 run 方法
    if (! $request->start()) {
        die("Start thread failed\n");
    }
    echo "Thread({$i}) started\n";
}

for ($i = 0; $i < 2; $i++) {
    // join 是阻塞的,所以指令碼執行時間取決於耗時最長的執行緒
    if (! $arr[$i]->join()) {
        die("Join failed\n");
    }
}

相關文章