0

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 ints to the already running thread?

Edit What I am basically doing is trying to implement the WS protocol:

<?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.

I am using pthreads

Ikari
  • 3,176
  • 3
  • 29
  • 34

1 Answers1

0

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). 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

tix3
  • 1,142
  • 8
  • 17
  • Have added some code in there ;-) could you explain the things a bit about the links given in the answer =) – Ikari Aug 26 '16 at 16:26