Last active
December 1, 2015 23:33
-
-
Save arleighdickerson/e042ba2514fceee46e8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace console\controllers; | |
use Yii; | |
use yii\console\Controller; | |
use yii\helpers\Json; | |
use yii\helpers\FileHelper; | |
class MultithreadingController extends Controller { | |
public $tempDir; | |
public $poolSize = null; | |
public function init() { | |
parent::init(); | |
$this->tempDir = FileHelper::normalizePath(sys_get_temp_dir()); | |
if ($this->poolSize === null) { | |
$this->poolSize = $this->getCores() - 1; | |
} | |
} | |
public function getCores() { | |
return intval(shell_exec("grep -c ^processor /proc/cpuinfo"), 10); | |
} | |
protected function writeCommandFile($actions) { | |
$filename = tempnam($this->tempDir, $this->id); | |
$handle = fopen($filename, "w"); | |
foreach ($actions as $action) { | |
list($actionId, $args) = $action; | |
fwrite($handle, './yii ' . $actionId . " '" . str_replace('"','\"',Json::encode($args)) . "'" . PHP_EOL); | |
} | |
fclose($handle); | |
return $filename; | |
} | |
public function runAsync($actions) { | |
$commands = $this->writeCommandFile($actions); | |
$maxProcs = $this->poolSize; | |
system("cat $commands | xargs -I CMD --max-procs=$maxProcs bash -c CMD"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment