pcntl研究

虽说php用于并发计算有点山寨,但总比没有强把。(有问题请指正)

下面是pcntl多线程的例子。(只能用于cli模式,而且只能用于linux环境)

<?php
$starttime=microtime();
$m = new Memcache;
$m->addServer('127.0.0.1', 11211);
$k=1;
$m->set('foo', 1);
//$m->set('key', 0);
for ($i = 1; $i <= 100; ++$i) {
$pid = pcntl_fork();

if (!$pid) {
//
//sleep(1);

//程序处理代码,memcache并发有问题,同时解决并发问题。
//$lock = "ss" . '.lck';
//$write_length = 0;
//while(true) {
//if( file_exists($lock) ) {
//usleep(100);
//} else {
//touch($lock);
//$m->set('foo', $m->get('foo')+1);
//echo $key=$m->get('foo');
print "In child $i ";
break;
}
}
if( file_exists($lock) ) {
unlink($lock);
}


exit($i);
}
}

while (pcntl_waitpid(0, $status) != -1) {
$status = pcntl_wexitstatus($status);
//echo $status;
echo "Child $status completed ";
}
$endtime=microtime();

?>

原文地址:https://www.cnblogs.com/liuwenbohhh/p/4795323.html