0

因此,假设我创建了一个线程并将其与主进程分离,然后启动它。

那么,在线程分离后,如何将一些数据块(如strings, 或ints )传递给已经运行的线程?

编辑 我基本上在做的是尝试实现 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

4

1 回答 1

0

实际的问题很模糊。你想做的事情在 IPC(进程间通信)下符合我的理解,可以通过几种方式实现(据我所知,最常见的一种是: http: //php.net/manual/en/function.stream -socket-pair.php)。我建议尽管您可以使用某种排队和轮询系统,如rabbitmq来传递消息。它会提供一些开销,但它是一个众所周知且高度使用的解决方案

于 2016-08-26T13:29:30.157 回答