我正在尝试使用pthread进行多线程编程。我使用构造函数创建了一个线程池。第一个参数是工作线程的数量。
$pool = new Pool(8, 'WebWorker');
我希望能够自动检测处理器核心数。就像这样:
$pool = new Pool(get_processor_cores_number(), 'WebWorker');
如何使用PHP实现呢?
如果服务器是Linux机器,您可以使用以下代码片段:
$ncpu = 1;
if(is_file('/proc/cpuinfo')) {
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$ncpu = count($matches[0]);
}
你可以像这样做,当然你的服务器应该是在Linux系统中:
function get_processor_cores_number() {
$command = "cat /proc/cpuinfo | grep processor | wc -l";
return (int) shell_exec($command);
}
cat /proc/cpuinfo | grep processor | wc -l
的方法非常冗长。你可以使用一个进程和一个管道来完成同样的操作:grep -c processor /proc/cpuinfo
。 - teknoraversubstr_count(file_get_contents("/proc/cpuinfo"),"processor");
- hanshenrik如果有人正在寻找一个简单的函数来获取 Windows 和 Linux 操作系统下的CPU核心总数,以下是相关内容:
function get_processor_cores_number() {
if (PHP_OS_FAMILY == 'Windows') {
$cores = shell_exec('echo %NUMBER_OF_PROCESSORS%');
} else {
$cores = shell_exec('nproc');
}
return (int) $cores;
}
这里有一个暴露sysconf的扩展:krakjoe/sysconf
<?php
$cpusConfigured = sysconf(SYSCONF_NPROCESSORS_CONF);
$cpusOnline = sysconf(SYSCONF_NPROCESSORS_ONLN);
?>
function get_total_cpu_cores() {
return (int) ((PHP_OS_FAMILY == 'Windows')?(getenv("NUMBER_OF_PROCESSORS")+0):substr_count(file_get_contents("/proc/cpuinfo"),"processor"));
}
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;
}
return (int)(rtrim(shell_exec('nproc')));
应该就足够了。 - hanshenrik\n
(换行符)-我在这里使用了rtrim()来删除换行符,但是cast-to-int无论如何都会忽略换行符,所以如果你喜欢微优化模因,抛弃rtrim()应该可以使它更快,而不改变功能。 - hanshenrik
$ncpu = substr_count((string)@file_get_contents('/proc/cpuinfo'),"\nprocessor")+1;
- 首先,substr_count比preg_match_all更快,我们只打开了一个文件而不是两个,如果文件无法读取,substr_count会返回0并且+1将0转换为1,但当文件可读时,substr_count会跳过第一个处理器,因为它不以换行符开头,而+1也考虑到了这一点 :) - hanshenrik/sys/devices/system/cpu/online
并读取 online 的 CPU :) - teknoraver