因此,假设我创建了一个线程并将其与主进程分离,然后启动它。
那么,在线程分离后,如何将一些数据块(如strings
, 或int
s )传递给已经运行的线程?
编辑 我基本上在做的是尝试实现 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
.
我正在使用pthread