进程,内存和协程
一、进程1.1 进程
进程就是一个程序==正在运行==的实例
$process = new swoole_process(function (swoole_process $pro){ $pro->exec("/home/work/study/soft/php/bin/php",[__DIR__.'/'.'../server/http_server.php']); },false); $pid = $process->start(); echo $pid.PHP_EOL; swoole_process::wait();
以树状图显示进程之间的关系命令
pstree -p 进程ID
启动成功后会创建一个master进程,2个manager进程,8个worker子进程,根据自己的设置
1.1.2 进程的使用场景
1.1.2 代码实现
echo "process-start-time:".date("Ymd H:i:s");
$workers = [];
$urls = [
'https://baidu.com',
'https://sina.com.cn',
'https://qq.com',
'https://baidu.com?search=singwa',
'https://baidu.com?search=singwa1',
'https://baidu.com?search=singwa2',
];
//创建多个子进程分别模拟请求URL的内容,同步进行
for($i = 0; $i < 6; $i++){
$process = new swoole_process(function(swoole_process $worker) use($i,$urls){
$content = curlData($urls[$i]);
//将内容写入管道
$worker->write($content.PHP_EOL);
},true);
$pid = $process->start();
$workers[$pid] = $process;
}
//获取管道的内容
foreach ($workers as $process){
echo $process->read();
}
/**
* @param $url
* @return string
* 模拟请求URL的内容
*/
function curlData($url){
sleep(2);
return $url . 'success'.PHP_EOL;
}
echo "process-end-time:".date("Ymd H:i:s");
二、内存
内存操作之模块==table==
使用场景:swoole_table一个基于共享内存和锁实现的超高性能,并发数据结构。用于解决多进程/多线程数据共享和同步加锁问题。==进程结束后内存会自动释放==
$table = new swoole_table(1024);
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING, 64);
$table->column('num', $table::TYPE_FLOAT);
$table->create();
$table->set('yfyjsz', ['id' => 1, 'name' => 'test1', 'num' => 20]);
$table['singwa'] = ['id'=>2,'name'=>'singwa','num'=>123]; //和set一样
$table->incr('singwa','num',2); //原子自增
print_r($table['singwa']);
print_r($table->get('yfyjsz'));
三、协程
$http = new swoole_http_server('0.0.0.0',9503);
$http->on('request',function ($request,$response){
$redis = new Swoole\Coroutine\Redis();
$redis->connect('127.0.0.1', 6379);
$val = $redis->get($request->get['a']);
$response->header('Content-type','text/plain');
$response->end($val);
});
$http->start();