takafumi blog

日々の勉強メモ

PHPのpthreadsでマルチスレッド

環境   CentOS 7.0 PHP 5.6

pthreadsを使ってみます。
PHP: pthreads - Manual
PHPを--enable-maintainer-ztsつきでインストールする必要ある。
CentOS7にPHP5.6をソースからインストール - takafumi blog

さてpthreadsをインストール

$ pecl install pthread
$ echo 'extension=pthreads.so' > /etc/php.d/pthreads.ini

確認

# iniファイル
$ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/pthreads.ini
# モジュール確認
$  php -m | grep pthreads
pthreads

適当にテストしてみる。

<?php
class MyThread extends Thread {
    private $num = 0;
    private $sleep = 0;
    public function __construct($num, $sleep)
    {
        $this->num = $num;
        $this->sleep = $sleep;
    }
    public function run()
    {
        $this->_run();
    }
    private function _run()
    {
        echo 'start thread' . $this->num . "\n";
        for ($i=0; $i<5; $i++) {
            sleep($this->sleep);
            printf('%d-%d,', $this->num, $i);
        }
        echo 'end thread' . $this->num . "\n";
    }
}

$thread1 = new MyThread(1, 3);
$thread2 = new MyThread(2, 1);
$thread3 = new MyThread(3, 2);

$thread1->start();
$thread2->start();
$thread3->start();


$ php MyThread.php

start thread1
start thread2
start thread3

2-0,2-1,3-0,1-0,2-2,2-3,3-1,2-4,end thread2
1-1,3-2,3-3,1-2,3-4,end thread3
1-3,1-4,end thread1

確かに並列で動いています。