0

我正在尝试实现一个脚本,该脚本以限制(5)启动线程异步并在所有线程都忙时等待。如果线程很忙,我的脚本必须等到一个空闲,它应该启动另一个,但由于某些原因确实卡住了。昨天我发现了 pthreads,今天几个小时后,这就是我带来的全部内容:

编辑:例如,有 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();
  }
}
?>

输出:

[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.

我知道这很原始,但我对 pthreads 完全陌生,所有示例都没有异步线程数限制。我的代码肯定有问题,但我不知道在哪里。

4

1 回答 1

0

如另一篇文章所述,问题是全局内存未共享。因此$active_thread,即使您使用global.

请参阅帖子:如何在 php 中跨线程共享全局变量?

于 2019-08-22T20:10:41.173 回答