线程PHP中的全局增量

Iva*_*vić 1 php multithreading pthreads

我正在运行4个同时运行的线程.(work()在这种情况下,线程同时运行功能)

global $i;
$i = 1;

function work($address) {
    while($i < 1000) {
        $i++;
        ----
        if($i == something) some job... 
        ----
    }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这不起作用.线程有时会在同一个圆圈中执行,因此我稍后会有一些重复的值.(可能他们有一些关键部分)任何想法如何解决这个问题?

Joe*_*ins 5

计数器对象必须是线程安全的,它还必须采用同步方法.

以下是此类代码的示例:

<?php
class Counter extends Threaded {

    public function __construct($value = 0) {
        $this->value = $value;
    }

    /** protected methods are synchronized in pthreads **/
    protected function increment() { return ++$this->value; }
    protected function decrement() { return --$this->value; }

    protected $value;
}

class My extends Thread {

    /** all threads share the same counter dependency */
    public function __construct(Counter $counter) {
        $this->counter = $counter;
    }

    /** work will execute from job 1 to 1000, and no more, across all threads **/        
    public function run() {
        while (($job = $this->counter->increment()) <= 1000) {
            printf("Thread %lu doing job %d\n", 
                Thread::getCurrentThreadId(), $job);
        }
    }

    protected $counter;
}

$counter = new Counter();
$threads = [];

while (($tid = count($threads)) < 4) {
    $threads[$tid] = new My($counter);
    $threads[$tid]->start();
}

foreach ($threads as $thread)
    $thread->join();
?>
Run Code Online (Sandbox Code Playgroud)

work()似乎是多余的,这个逻辑最有可能在:: run函数中.