8
5

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編)

Last updated at Posted at 2017-02-21

PHPは最近の他の言語とは違ってシングルスレッドなので、一回のリクエストで複数の処理を同時に実行したりといったことは通常はできない。

##プロセスフォーク

process_fork
<?php
$pid = pcntl_fork();
if($pid == -1){
	die("Cannot fork");//フォーク失敗
}else if($pid){
	echo "I am parent!\n";//親プロセス側
	pcntl_wait($status);//子プロセス終了を待機しゾンビプロセス化を防ぐ
}else{
	echo "I am child!\n";//子プロセス側
}
?>

##マルチスレッドプログラミング
ここではpthreadsモジュールを用いる。

pthread
<?php
class ThreadTest extends Thread{//Threadを継承したクラスがスレッドオブジェクトに
    //start時に呼び出される
    public function run(){
        sleep(10);//10秒待機
        echo "Thread finished.\n";
    }
}
$th1 = new ThreadTest();
$th1->start();//開始

var_dump($th1->isRunning());//Thread::runがまだ実行中か->true

$th1->join();//スレッドが終わるまで待機

//$th1->kill(); //スレッドの強制終了。非推奨

echo "Finished.\n"
?>

>引用: http://qiita.com/rana_kualu/items/02f380f2f3d5020051bb
8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?