我必须分析很多信息。 为了加快速度,我将在同一时刻运行相同脚本的多个实例。
然而,脚本很可能会分析我不喜欢的同一条信息(重复),因为它会减慢过程。
如果只运行一个实例,我用数组解决了这个问题(我保存了已经分析的内容)。
所以我有一个问题,我怎么能以某种方式将该数组与其他“线程”同步?
MySQL是一个选项,但我想它会有点矫枉过正? 我还阅读了有关内存共享的内容,但不确定这是否是我正在寻找的解决方案。
所以,如果有人有一些建议,请告诉我。
此致
答案 0 :(得分:1)
使用真正的多线程这是一项微不足道的任务:
<?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);
?>
您的用例不一定需要slog()函数,但认为显示具有可读输出的可执行示例很有用。
它的主要要点是多个线程只需要引用一组公共数据来操作该数据......