gpt4 book ai didi

php - Pthreads PHP : execute Foreach Loop in Parallel

转载 作者:行者123 更新时间:2023-12-03 12:49:12 26 4
gpt4 key购买 nike

如何将核心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

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

关于php - Pthreads PHP : execute Foreach Loop in Parallel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com