简体   繁体   English

如何将一些数据传递给PHP中正在运行的线程?

[英]How to pass some data to a running thread in PHP?

So let's say I create a thread and detach it from the main process, and start it. 假设我创建了一个线程并将其与主进程分离,然后启动它。

So, after the thread is detached, how is it possible to pass some chunks of data like strings , or int s to the already running thread? 因此,在分离线程之后,如何将某些数据块(例如stringsint传递给已经运行的线程?

Edit What I am basically doing is trying to implement the WS protocol: 编辑我基本上在做的是尝试实现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();

I found various answers related to passing data to a running thread, but I couldn't find any specifically for PHP . 我找到了各种与将数据传递给正在运行的线程有关的答案,但是找不到专门针对PHP答案。

I am using pthreads 我正在使用pthreads

The actual question is quite vague. 实际问题很模糊。 What you want to do falls to my understanding under the IPC (interprocess communication) and can be implemented with a couple of ways (to my knowledge the most common one is : http://php.net/manual/en/function.stream-socket-pair.php ). 您想做的事取决于我在IPC(进程间通信)下的理解,并且可以通过两种方法来实现(据我所知,最常见的方法是: http : //php.net/manual/en/function.stream -socket-pair.php )。 I would suggest though that you could use some kind of queueing and polling system like rabbitmq to pass around messages.It will provide some overhead but its a well known and highly used solution 我建议您可以使用某种形式的排队和轮询系统(例如rabbitmq)来传递消息,它将提供一些开销,但它是众所周知且使用率很高的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM