所以,让我说我创建一个线程并将其从主进程中分离出来,然后启动它。
因此,在分离线程之后,如何将一些数据块(如strings
或int
}传递给已经运行的线程?
修改的 我基本上正在尝试实现WS协议:
<?php
// Pseudo-Code
class LongRunningThread extends \Thread {
private $handshakeReq;
public function __construct(Request $handshakeRequest) {
$this->handshakeReq = $handshakeRequest;
}
public function run() {
// Do handshake
// But do not exit, because after the handshake is done the socket connection needs to be maintained.
// Probably some trigger which notifies that a new message is here and the message arrives <automagically>
if(trigger) {
$message = $message;
$this->onNewWsMessage($message);
}
}
public function onNewWsMessage(string $rawMessage) {
// Process the message...
}
}
$stream = stream_socket_server(sprintf("tcp://%s:%d",
"localhost",
1337
), $errno, $errmsg);
// Boiler plate, and connection acceptance (blah blah blah)
// $client is the the accepted connection
$message = fread($client, 4096);
// Cannot pass the $client in here because the instability of resources with threads
// as passing them here, apparently converts them to <bool> false
$longRunningThread = new \LongRunningThread($message);
$longRunningThread->start() && $longRunningThread->join();
我找到了与将数据传递给正在运行的线程相关的各种答案,但我无法找到专门用于PHP
的答案。
我正在使用pthreads
答案 0 :(得分:0)
实际问题很模糊。 您想要做什么属于我在IPC(进程间通信)下的理解,并且可以通过几种方式实现(据我所知,最常见的方式是:http://php.net/manual/en/function.stream-socket-pair.php)。 我建议虽然您可以使用某种排队和轮询系统(如rabbitmq)来传递消息。它会提供一些开销,但它是一个众所周知且使用频繁的解决方案