【问题标题】:Pthreads PHP : execute Foreach Loop in ParallelPthreads PHP:并行执行 Foreach 循环
【发布时间】:2023-03-29 18:07:01
【问题描述】:

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

我的核心 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 循环后没有多线程)

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

【问题讨论】:

    标签: php multithreading foreach pthreads


    【解决方案1】:

    包括评论。

    <?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() { } };
    

    【讨论】:

    • @Michael thnx ......你能告诉我最后两个 stackableArray 和 Storage 类有什么用吗?多线程后如何在普通 PHP 中使用所有 $this->Storage[$this->Storage['count']] 数组值
    • @JoeWatkins 我会在实际示例中这样做,但我只是将原始代码移植为多线程。
    • @Melody 这些类是线程间共享数据所必需的。线程之间不能共享普通数组。
    • @Melody 线程完成后,主进程可以将对象转换回普通数组并对其进行操作...或者您可以在对象上使用内置的 ArrayAccess ...
    • @Pierre 我想我之前可能使用过 for() 循环,我认为它只是用于数组追加的 []。
    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2019-07-15
    相关资源
    最近更新 更多