V
V
Vladimir Goncharov2014-02-17 22:37:19
PHP
Vladimir Goncharov, 2014-02-17 22:37:19

How to implement a timer in php that works in conjunction with stream_select?

There is code that fires when an event arrives on one of the listening sockets.

while (true) {
    //формируем массив прослушиваемых сокетов:
    $read = $connects;
    
    stream_select($read, $write, $except, null);//ожидаем сокеты доступные для чтения (без таймаута)
        ...обрабатываем $read
}

You also need to trigger the timer 20 times per second.
If you use a timeout for this:
stream_select($read, $write, $except, 0.05));
then the processor is constantly loaded at 100% (which is what they warn on php.net that stream_select with timers does not work efficiently)
My task can be easily solved using libevent:
$this->base = event_base_new();
$timer = event_timer_new();
event_timer_set($timer, array($this, '_onTimer'), $timer);
event_base_set($timer, $this->base);
event_timer_add($timer);

But I need to solve the problem without using libevent.
Now I solve the problem like this: I create a pair socket using stream_socket_pair(), I do fork()it and in the child process in an endless loop I write data to the pair socket $ parent:
while (true) {
    fwrite('ping', $parent);
    usleep(50000);
}

In the parent process, I listen on the $child socket pair, which is associated with the child:
$read = [$child];
This allows me to achieve the desired effect with zero CPU usage.
Is there any way to create sockets that would fall off on timeout, so that the stream_select function would work with this event, so that the code would be similar to libevent?
I'll warn you right away that tick does not work in this case, because while stream_select is waiting for events on listening sockets, "ticks" do not occur.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rowdy Ro, 2014-02-17
@rowdyro

There is a puff extension www.php.net/manual/en/class.thread.php but I'm not aware of its quality. One blocking thread reads, the other does the necessary things 20 times per second.
There was a similar task, multithreading is not very friendly with puff, I wrote a layer in C ++

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question