Skip to content

Instantly share code, notes, and snippets.

@mahadirz
Last active August 29, 2015 14:23
Show Gist options
  • Save mahadirz/00411bcd60675190457b to your computer and use it in GitHub Desktop.
Save mahadirz/00411bcd60675190457b to your computer and use it in GitHub Desktop.
PHP Multithread
<?php
/**
* Created by PhpStorm.
* User: Mahadir
* Date: 6/22/2015
* Time: 7:23 AM
*
* Forking 50 threads which each thread
* have processing time within 0-3 seconds
* The Total Execution Time should be
* around 3.xx seconds
*
*/
class WorkerThreads extends Thread
{
private $workerId;
public $seconds;
public function __construct($id)
{
$this->workerId = $id;
}
public function run()
{
$sleep = rand(0, 3);
sleep($sleep);
echo "Worker {$this->workerId} took $sleep seconds <br>\n" ;
$this->seconds = $sleep;
if($sleep){
die();
}
}
}
$time_start = microtime(true);
// Worker pool
/**
* @var WorkerThreads
*/
$workers = [];
$range = range(0, 50);
// Initialize and start the threads
foreach ($range as $i) {
$workers[$i] = new WorkerThreads($i);
$workers[$i]->start();
}
// Let the threads come back
foreach ($range as $i) {
$workers[$i]->join();
}
//total seconds per thread
$totalSeconds =0;
foreach ($range as $i) {
$totalSeconds = $totalSeconds + $workers[$i]->seconds;
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
//execution time of the script
echo '<br><b>Total Execution Time:</b> '.$execution_time.' Seconds';
echo "<br><b>Without multithreading execution time would take:</b> ".$totalSeconds." seconds";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment