0

我必须分析很多信息。为了加快速度,我将同时运行同一脚本的多个实例。

但是,脚本很有可能会分析我不喜欢的相同信息(重复),因为它会减慢进程。

如果只运行 1 个实例,我用数组解决这个问题(我保存已经分析过的内容)。

所以我有一个问题,我怎么能以某种方式将该数组与其他“线程”同步?

MySQL是一种选择,但我想它会是矫枉过正吗?我还阅读了有关内存共享的信息,但不确定这是否是我正在寻找的解决方案。

因此,如果有人有任何建议,请告诉我。

问候

4

1 回答 1

1

This is a trivial task using real multi-threading:

<?php
/* we want logs to be readable so we are creating a mutex for output */
define ("LOG", Mutex::create());
/* basically a thread safe printf */
function slog($message, $format = null) {
    $format = func_get_args();
    if ($format) {
        $message = array_shift($format);

        if ($message) {
            Mutex::lock(LOG);
            echo vsprintf(
                $message, $format);
            Mutex::unlock(LOG);
        }
    }
}

/* any pthreads descendant would do */
class S extends Stackable {
    public function run(){}
}

/* a thread that manipulates the shared data until it's all gone */
class T extends Thread {
    public function __construct($shared) {
        $this->shared = $shared;
    }
    public function run() {
        /* you could also use ::chunk if you wanted to bite off a bit more work */
        while (($next = $this->shared->shift())) {
            slog(
                "%lu working with item #%d\n", $this->getThreadId(), $next);
        }
    }
}

$shared = new S();
/* fill with dummy data */
while (@$o++ < 10000) {
    $shared[]=$o;
}

/* start some threads */
$threads = array();
while (@$thread++ < 5) {
    $threads[$thread] = new T($shared);
    $threads[$thread]->start();
}

/* join all threads */
foreach ($threads as $thread)
    $thread->join();

/* important; ::destroy what you ::create */
Mutex::destroy(LOG);
?>

The slog() function isn't necessarily required for your use case, but thought it useful to show an executable example with readable output.

The main gist of it is that multiple threads need only a reference to a common set of data to manipulate that data ...

于 2013-09-08T08:03:58.257 回答