3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでマルチスレッド

Posted at

PHPでマルチスレッドは、あまり需要が無いかもしれませんが。

親プロセスでは、6つの子プロセスを立てる事をしてます。
それぞれの子プロセス内では1から10の乱数を発生させ、
その数値が10だった場合自身のプロセスを終了させるという簡単なものです。

<?php
define("MAX_PROCESS",6);
define("TIMEOUT",10);

$oControl = new main();
class main
{
    private $_MAX_PROCESS = MAX_PROCESS;
    private $_TIMEOUT = TIMEOUT;

    function main()
    {
        for( $i = 1; $i<= $this->_MAX_PROCESS; $i++ ) {
            $pid = pcntl_fork();
            if ( $pid == -1 ) {
                die( "fork できません\n" );
            } else if ( $pid ) {
                $pids[ $pid ] = TRUE;
                if ( count( $pids ) >= $this->_MAX_PROCESS ) {
                    unset( $pids[ pcntl_waitpid( -1, $status, WUNTRACED ) ] );
                }
            } else {
                $this->childProcess($i);
            }
        }
        while ( count( $pids ) > 0 ) {
            unset( $pids[ pcntl_waitpid( -1, $status, WUNTRACED ) ] );
        }
    }

    function childProcess($my_number)
    {
        while(1){
            // 強制終了時間を指定
            pcntl_alarm( $this->_TIMEOUT );
            $rand = mt_rand(1,10);
            $message = "number=$my_number rand=$rand";
            if( $rand == $this->_TIMEOUT ) {
                $message .= " end";
            }
            $message .= PHP_EOL;
            echo $message;
            sleep( $rand );
        }
        return true;
    }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?