phpday 2027 - Call for Papers

Io\Poll\Context::wait

(PHP 8 >= 8.6.0)

Io\Poll\Context::wait — Waits for events on the watched handles

説明

public function Io\Poll\Context::wait(?Time\Duration $timeout = null, ?int $maxEvents = null): array

Blocks until at least one watched handle is ready or the timeout expires, and returns the watchers whose events were triggered.

Unless Io\Poll\Event::EdgeTriggered or Io\Poll\Event::OneShot is used, a watcher is returned by every call for as long as its condition holds, for example until the pending data has been read. Such a watcher for Io\Poll\Event::Read on a stream is also returned while unread data remains in the read buffer of the stream.

If the context has no active watcher, the call returns an empty array once the timeout expires. Without a timeout the behavior depends on the backend: the call either returns immediately or blocks indefinitely, so it should not be relied upon.

パラメータ

timeout

The maximum time to wait. A zero duration makes the method return immediately, and null waits without a time limit.

maxEvents

The maximum number of watchers to return in one call. With null, the backend chooses a value based on the number of watched handles. The other watchers that are ready are not returned by this call.

戻り値

Returns a list of the Io\Poll\Watcher objects that were triggered, or an empty array if none was. The events of each watcher are available from Io\Poll\Watcher::getTriggeredEvents() and Io\Poll\Watcher::hasTriggered().

エラー / 例外

Throws a ValueError if timeout is negative.

Throws a ValueError if maxEvents is less than 1 or greater than 2147483647.

Throws an Io\Poll\FailedPollWaitException if the backend fails to wait for events.

例

例1 Io\Poll\Context::wait() example

<?php
use Io\Poll\Context;
use Io\Poll\Event;
use Time\Duration;

[$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

$context = new Context();
$context->add(new StreamPollHandle($reader), [Event::Read], 'reader');
$context->add(new StreamPollHandle($writer), [Event::Write], 'writer');

// Only the writing end is ready.
foreach ($context->wait(Duration::fromMilliseconds(100)) as $watcher) {
    echo $watcher->getData(), PHP_EOL;
}

fwrite($writer, 'ping');

// Both ends are ready, but at most one watcher is returned.
var_dump(count($context->wait(Duration::fromMilliseconds(100), 1)));

上の例の出力は以下となります。

writer
int(1)

参考

  • Io\Poll\Context::add() - Starts watching a handle
  • Io\Poll\Watcher::getTriggeredEvents()
  • Time\Duration
  • stream_select() - select() システムコールと同等の操作を、 ストリームの配列に対して seconds と microseconds で指定されたタイムアウト時間をもって行う
+add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top