dongxi7722 2015-04-27 16:35 采纳率: 0%
浏览 30
已采纳

将值返回给调用线程

I'm trying to use pthreads in PHP in an attempt to speed up a series of calculations that at the moment max out one CPU core for several seconds. I have split the calculations into a number of ranges and am running each range in the parent thread:

    $threads = array();
    foreach($cp as $c) {
        $threads[$c] = new ThreadedMatcher($params);
        $threads[$c]->start();
    }

I then want to array_merge the arrays created in each child thread (for each range) in the parent thread to get a value over the whole data set.

I gather that I need to use join() in the parent thread to wait for a thread to finish but how do I actually get a value out of the child thread into the parent thread?

  • 写回答

2条回答 默认 最新

  • dongxi0523 2015-05-01 01:14
    关注

    Try this:

    This will split the Payload according to your available cores, looping across batches, not to exceed the available Cpus maximum threads. I am using this very simple principle over many other Pthreads possibilities I have tested. Simplest and most efficient one for me so far.

    Works flawlessly with xenons servers and 80 available Cpus threads over 100M iterations for hours.

    $Pay_Load=array(
    array('id'=>$id,'query'=>$query1,'param'=>$param1),
    array('id'=>$id,'query'=>$query2,'param'=>$param2),
    /*... can be hundreds...just an example...*/
    )
    
    $Nb_of_Cpus=4;
    $Nb_of_threads=$Nb_of_Cpus*2;
    $Batch_Works=array_chunk($Pay_Load,$Nb_of_threads);
    
    $threads = [];
    $results = array();
    
    foreach ($Batch_Works as $batch) {
        foreach ($batch as $key => $params) {
            $threads[$key] = new ThreadedMatcher($params);
            $threads[$key]->start();
        }
        foreach ($batch as $key => $params) {
            $threads[$key]->join();
            $returned_result=$threads[$key]->result;
            $returned_id=$threads[$key]->id;
            $result=array('id'=>$returned_id,'result'=>$returned_result);
            array_push($results, result);    
        }
    }
    /* all returned results are now in the same array */
    /* with the original Payload id as an example here */
    var_dump($results);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀