I'm trying to use pthreads for multithreading. I'm creating pool with constructor. First parameter is number of Workers.
$pool = new Pool(8, 'WebWorker');
I want to detect count of processor cores automatically. Something like this:
$pool = new Pool(get_processor_cores_number(), 'WebWorker');
How is it possible with PHP?
You can do something like that, of course your server should be in linux:
function get_processor_cores_number() {
$command = "cat /proc/cpuinfo | grep processor | wc -l";
return (int) shell_exec($command);
}
You will execute a shell command then cast it to int.
Here is an extension exposing sysconf: krakjoe/sysconf
<?php
$cpusConfigured = sysconf(SYSCONF_NPROCESSORS_CONF);
$cpusOnline = sysconf(SYSCONF_NPROCESSORS_ONLN);
?>
Most applications only care about the number configured.
If the server is a Linux machine you can do it with the following snippet:
$ncpu = 1;
if(is_file('/proc/cpuinfo')) {
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$ncpu = count($matches[0]);
}
In my own library, I have a function for this among other things. You can easily modify it where it uses nonstandard PHP functions.
For instance, I cache the result so you can ignore that. Then I have functions to check if we are running on Linux, Mac or Windows. You could insert a similar check of your own there. For executing the actual system specific check I use my own Process
class which allows things such as reconnecting to running processes on subsequent requests to check status, output etc. But you can change that and just use exec
.
public static function getNumberOfLogicalCPUCores() {
$numCores = CacheManager::getInstance()->fetch('System_NumberOfLogicalCPUCores');
if(!$numCores) {
if(System::isLinux() || System::isMac()) {
$getNumCoresProcess = new Process("grep -c ^processor /proc/cpuinfo");
$getNumCoresProcess->executeAndWait();
$numCores = (int)$getNumCoresProcess->getStdOut();
}
else if(System::isWindows()) {
// Extract system information
$getNumCoresProcess = new Process("wmic computersystem get NumberOfLogicalProcessors");
$getNumCoresProcess->executeAndWait();
$output = $getNumCoresProcess->getStdOut();
// Lazy way to avoid doing a regular expression since there is only one integer in the output on line 2.
// Since line 1 is only text "NumberOfLogicalProcessors" that will equal 0.
// Thus, 0 + CORE_COUNT, which equals CORE_COUNT, will be retrieved.
$numCores = array_sum($getNumCoresProcess->getStdOutAsArray());
}
else {
// Assume one core if this is some unkown OS
$numCores = 1;
}
CacheManager::getInstance()->store('System_NumberOfLogicalCPUCores', $numCores);
}
return $numCores;
}