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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了