Ric*_*hez 6 php fork asynchronous codeigniter
我在 CodeIgniter - Ubuntu Server 上运行我的代码。
我一直在研究运行函数的异步方法。
这是我的功能:
<?php
// Registers a new keyword for prod to the DB.
public function add_keyword() {
$keyword_p = $this->input->post('key_word');
$prod = $this->input->post('prod_name');
$prod = $this->kas_model->search_prod_name($prod);
$prod = $prod[0]->prod_id;
$country = $this->input->post('key_country');
$keyword = explode(", ", $keyword_p);
var_dump($keyword);
$keyword_count = count($keyword);
echo "the keyword count: $keyword_count";
// problematic part that needs forking
for ($i=0; $i < $keyword_count ; $i++) {
// get new vars from $keyword_count
// run API functions to get new data_arrays
// inserts new data for each $keyword_count to the DB
}
// Redirect to main page.
redirect('banana/kas');
}
Run Code Online (Sandbox Code Playgroud)
“foreach”使用带有慢速 API 的变量,并更新数据库。
我看到了一些使用 fork 的教程,但还没有完全理解它的语法部分。我发现的大部分内容只是对其工作原理的解释(2 个进程:父子等),但没有很好地解释如何将其应用于代码。
有人可以解释我如何使用 fork() 语法吗?
http://www.onlinetechtutorials.com/2014/06/how-to-run-php-code-asynchronously.html
http://php.net/manual/en/function.pcntl-fork.php(更通用)
从服务器端:https : //www.youtube.com/watch?v=xVSPv-9x3gk
编辑:
我做对了吗?
<?php
// Registers a new keyword for prod to the DB.
public function add_keyword() {
$keyword_p = $this->input->post('key_word');
$prod = $this->input->post('prod_name');
$prod = $this->kas_model->search_prod_name($prod);
$prod = $prod[0]->prod_id;
$country = $this->input->post('key_country');
$keyword = explode(", ", $keyword_p);
var_dump($keyword);
$keyword_count = count($keyword);
echo "the keyword count: $keyword_count";
for ($i=0; $i < $keyword_count ; $i++) {
// create your next fork
$pid = pcntl_fork();
if(!$pid){
//*** get new vars from $keyword_count
//*** run API functions to get new data_arrays
//*** inserts new data for each $keyword_count to the DB
print "In child $i\n";
exit($i);
// end child
}
}
// we are the parent (main), check child's (optional)
while(pcntl_waitpid(0, $status) != -1){
$status = pcntl_wexitstatus($status);
echo "Child $status completed\n";
}
// your other main code: Redirect to main page.
redirect('banana/kas');
}
?>
Run Code Online (Sandbox Code Playgroud)
在循环中使用 this 不会造成任何问题吗?它会知道堆叠每个进程吗?
小智 1
你在 pcntl_fork() 之后有一个 fork,检查 $pid 然后你就可以使用它了。重复此操作以获取更多叉子。
<?php
for($i = 1; $i <= 3; ++$i){
// create your next fork
$pid = pcntl_fork();
if(!$pid){
// begin child, your execution code
sleep(1);
print "In child $i\n";
exit($i);
// end child
}
}
// we are the parent (main), check child's (optional)
while(pcntl_waitpid(0, $status) != -1){
$status = pcntl_wexitstatus($status);
echo "Child $status completed\n";
}
// your other main code
?>
Run Code Online (Sandbox Code Playgroud)
对于异步http请求,您可以使用multicurl: http: //php.net/manual/en/function.curl-multi-init.php
归档时间: |
|
查看次数: |
4978 次 |
最近记录: |