Pthreads PHP:并行执行Foreach循环 [英] Pthreads PHP : execute Foreach Loop in Parallel

查看:305
本文介绍了Pthreads PHP:并行执行Foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将代码从核心PHP转换为Pthread代码

How to convert code from core PHP to Pthread code

我的核心PHP代码:

require_once 'xyz.php';
$count="0";

foreach($sites as $site)
{
require_once 'allsite/'.$site.'.php';
$siteObj = new $site;
$data[$count] = $siteObj->getsiteData($query,$cat);
$count++;
}

我如何以Pthread方式执行foreach循环代码(多线程)

foreach循环执行后,完成了正常的PHP工作(foreach循环后没有多线程)

After foreach loop execution complete normal PHP stuff done (Means No Multi-Threading after foreach Loop)

注意::我已经在PHP中安装并配置pthread

Note : I already installed and config pthread in PHP

推荐答案

已包含评论.

<?php

//Require Core Component
require_once("xyz.php");

$Threads = new StackableArray();

//A Global Storage that will be shared between threads.
$Storage = new Storage();

//Store {count} in Global Storage
$Storage['count'] = 0;


/*
 * For Each Site, spawn a new thread, process the site and store result in Global Storage.
 */
foreach($sites as $site)
{
    $Thread = new SiteProcess($Storage, $site);
    $Thread->start();
    $Threads[$re] = $Thread;
}

//When the threads are complete, join them(destroy the threads)
foreach($Threads as $Thread)
{
    $Thread->join();
}

//A thread class
class SiteProcess extends Threads
{
    private $Storage;
    private $site;

    public function __construct(Storage $Storage, $site)
    {
        $this->Storage = $Storage;
        $this->site = $site;
    }

    public function run()
    {
        require_once("allsite/{$this->site}.php");
        $siteObj = new $this->site;
        $this->Storage[$this->Storage['count']] = $siteObj->getsiteData($query, $cat);
        $this->Storage['count'] = $this->Storage['count'] + 1;
    }
}

class StackableArray extends Stackable { public function run() { } };

class Storage extends Stackable { public function run() { } };

这篇关于Pthreads PHP:并行执行Foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆