简体   繁体   English

PHP pthreads与线程号异步卡住

[英]PHP pthreads async with threads number gets stuck

I'm trying to achive a script that start threads async with a limit(5) and does wait if all threads are busy. 我正在尝试获取一个脚本,该脚本以limit(5)启动异步线程,并在所有线程繁忙时等待。 If the threads are busy my script has to wait untill one is free and it should start another one but for some reasons does get stuck. 如果线程繁忙,我的脚本必须等到一个空闲后才能启动另一个脚本,但是由于某些原因,它确实卡住了。 Yesterday I discovered pthreads and after a few hours today this is all I came with: 昨天我发现了pthreads,今天过了几个小时,这就是我所拥有的一切:

EDIT: There are examples with 500 threads for example but in my case I need to parse large files(a few MBs) of targets and I need to make it to work async. 编辑:例如,有500个线程的示例,但就我而言,我需要解析目标的大文件(几MB),并且需要使其异步工作。

<?php
class My extends Thread {
  public function run() {
    echo $this->getThreadId() . "\n";
    sleep(rand(1, 3)); // Simulate some work...
    global $active_threads;
    $active_threads = $active_threads - 1; // It should decrese the number of active threads. Here could be the problem?
  }
}

$active_threads = 0;
$maximum_threads = 5;

while(true) {
  if($active_threads == $maximum_threads) {
    echo 'Too many threads, just wait for a moment untill some threads are free.' . "\n";
    sleep(3);
    continue;
  }

  $threads = array();
  for($i = $active_threads; $i < $maximum_threads; $i++) {
    $active_threads = $active_threads + 1;
    $threads[] = new My();
  }

  foreach($threads as $thread) {
    $thread->start();
  }
}
?>

Output: 输出:

[root@localhost tests]# zts-php test
140517320455936
140517237061376
140517228668672
140517220275968
140517207701248
Too many threads, just wait for a moment.
Too many threads, just wait for a moment.
Too many threads, just wait for a moment.
Too many threads, just wait for a moment.

I know is pretty primitive but I'm totally new to pthreads and all the examples are without async threads number limit. 我知道这很原始,但是我对pthreads完全陌生,所有示例都没有异步线程数限制。 There is for sure something wrong in my code but I have no ideea where. 我的代码中肯定有错误,但是我在哪里没有想法。

The problem as stated in another post is that the global memory is not shared. 在另一篇文章中指出的问题是不共享全局内存。 So your $active_thread will not decrement even if you use global . 因此,即使您使用global您的$active_thread也不会减少。

See post: How to share global variable across thread in php? 请参阅文章: 如何在php中的线程之间共享全局变量?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM