Io\Poll

new Io\Poll\Context(); $ctx->add(Io\Poll\Handle $handle, array $events): Io\Poll\Watcher; $ctx->wait(?Time\Duration $timeout = null): array; $watcher->hasTriggered(Io\Poll\Event $e): bool; $watcher->getTriggeredEvents(): array

New in PHP 8.6: epoll/kqueue/event-ports/WSAPoll-grade I/O multiplexing — breaks past stream_select's 1024-descriptor ceiling and returns readiness as Watcher objects; wait takes a Time\Duration outright.

C C23

C23
#include <stdio.h>
#include <poll.h>
#include <unistd.h>

int main(void) {
    int fds[2];
    pipe(fds); // fds[0] = read end (POSIX)

    /* poll(2): the portable face of readiness polling. Production
       servers reach for epoll(7) on Linux, kqueue(2) on the BSDs and
       macOS, event ports on Solaris, WSAPoll on Windows. */
    struct pollfd p = {fds[0], POLLIN, 0};
    int n = poll(&p, 1, 50); // empty pipe: timeout
    printf("empty-pipe: %d\n", n);

    write(fds[1], "ping", 4);
    p.revents = 0;
    n = poll(&p, 1, 1000); // pending data: readable
    printf("data-ready: %d\n", n);

    char buf[8] = {0};
    read(fds[0], buf, 4);
    printf("%s\n", buf);
    return 0;
}
Output
empty-pipe: 0
data-ready: 1
ping

C++ C++26

C++26
#include <cstdio>
#include <poll.h>
#include <unistd.h>

int main() {
    int fds[2];
    pipe(fds); // fds[0] = read end (POSIX)

    // poll(2) is the portable core; production C++ servers sit on
    // epoll/kqueue via asio or similar, same split as PHP's Io\Poll.
    pollfd p = {fds[0], POLLIN, 0};
    int n = poll(&p, 1, 50);
    std::printf("empty-pipe: %d\n", n);

    write(fds[1], "ping", 4);
    p.revents = 0;
    n = poll(&p, 1, 1000);
    std::printf("data-ready: %d\n", n);

    char buf[8] = {0};
    read(fds[0], buf, 4);
    std::printf("%s\n", buf);
    return 0;
}
Output
empty-pipe: 0
data-ready: 1
ping

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

// Socket.Select is the select(2)-family call in .NET: it scales like
// select, while the runtime's async I/O sits on epoll/kqueue internally —
// the same "select vs poll" split PHP 8.6 closes with Io\Poll.
var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect((IPEndPoint)listener.LocalEndPoint!);
var server = listener.Accept();
listener.Close();

var write = new List<Socket>();
var error = new List<Socket>();

var read = new List<Socket> { server };
Socket.Select(read, write, error, 50_000); // no data: times out
Console.WriteLine($"empty-pipe: {read.Count}");

client.Send(Encoding.ASCII.GetBytes("ping"));
read = new List<Socket> { server };
Socket.Select(read, write, error, 1_000_000);
Console.WriteLine($"data-ready: {read.Count}");

var buf = new byte[8];
int len = server.Receive(buf);
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, len));
Output
empty-pipe: 0
data-ready: 1
ping

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan string, 1)

	// Go programs never poll by hand: the runtime netpoller (epoll or
	// kqueue underneath) parks the goroutine and wakes it on readiness.
	select {
	case v := <-ch:
		fmt.Println("data-ready:", v)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("empty-pipe: 0")
	}

	ch <- "ping"
	select {
	case v := <-ch:
		fmt.Println("data-ready:", v)
	case <-time.After(time.Second):
		fmt.Println("empty-pipe: 0")
	}
}
Output
empty-pipe: 0
data-ready: ping

Java v27.0.1

v27.0.1
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;

public class Main {
    public static void main(String[] args) throws Exception {
        // NIO Selector is Java's Io\Poll: interest sets (OP_READ) on a
        // channel, ready keys returned per wait. Pipe = local pair, no network.
        Pipe pipe = Pipe.open();
        Selector selector = Selector.open();
        pipe.source().configureBlocking(false);
        pipe.source().register(selector, SelectionKey.OP_READ);

        int n = selector.select(200); // empty pipe: timeout
        System.out.println("empty-pipe: " + n);

        pipe.sink().write(ByteBuffer.wrap("ping".getBytes()));
        n = selector.select(1000);
        System.out.println("data-ready: " + n);

        ByteBuffer buf = ByteBuffer.allocate(8);
        pipe.source().read(buf);
        System.out.println(new String(buf.array(), 0, buf.position()));
    }
}
Output
empty-pipe: 0
data-ready: 1
ping

JavaScript v26.13.1

v26.13.1
const net = require('node:net');

// JS has no polling API to reach for: the event loop multiplexes every
// socket for you (epoll/kqueue under the hood), and readiness arrives
// as events, not return values.
const server = net.createServer((conn) => {
  conn.on('data', (chunk) => {
    console.log('data-ready: 1');
    console.log(chunk.toString().trim());
    conn.end();
    server.close();
  });
});
server.listen(0, '127.0.0.1', () => {
  const port = server.address().port;
  const client = net.createConnection(port, '127.0.0.1', () => {
    console.log('empty-pipe: 0');
    setTimeout(() => client.write('ping\n'), 20);
  });
});
Output
empty-pipe: 0
data-ready: 1
ping

PHP v8.6.0

v8.6.0
use Time\Duration;

// Io\Poll picks epoll/kqueue/event ports/WSAPoll per platform
$poll = new Io\Poll\Context();
var_dump($poll->getBackend() instanceof Io\Poll\Backend);

// a local socket pair stands in for a real connection
[$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
stream_set_blocking($reader, false);
$poll->add(new StreamPollHandle($reader), [Io\Poll\Event::Read]);

// nothing pending: the wait times out and returns no watchers
var_dump($poll->wait(Duration::fromMilliseconds(50)) === []);

fwrite($writer, 'ping');
$ready = $poll->wait(Duration::fromMilliseconds(1000));
var_dump(count($ready) === 1);
var_dump($ready[0]->hasTriggered(Io\Poll\Event::Read));
var_dump($ready[0]->getTriggeredEvents() === [Io\Poll\Event::Read]);
var_dump(fread($reader, 4));

// drop the interest and close
$ready[0]->remove();
fclose($reader);
fclose($writer);
Output
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
string(4) "ping"

Python v3.15.2

v3.15.2
import selectors
import socket

# selectors.DefaultSelector picks epoll/kqueue/select per platform —
# the Python standard library's own Io\Poll.
sel = selectors.DefaultSelector()
reader, writer = socket.socketpair()
reader.setblocking(False)
sel.register(reader, selectors.EVENT_READ)

n = len(sel.select(timeout=0.2))  # empty pipe: no ready events
print(f"empty-pipe: {n}")

writer.sendall(b"ping")
n = len(sel.select(timeout=1))
print(f"data-ready: {n}")
print(reader.recv(4).decode())
Output
empty-pipe: 0
data-ready: 1
ping

Rust v1.99.1

v1.99.1
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use std::time::Duration;

const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
const ACCEPTED: Token = Token(2);

fn main() {
    // mio is Rust's Io\Poll: epoll/kqueue/IOCP behind one Poll type,
    // readiness delivered as token-tagged events.
    let mut poll = Poll::new().unwrap();
    let mut events = Events::with_capacity(8);

    let mut listener = TcpListener::bind("127.0.0.1:0".parse().unwrap()).unwrap();
    let local = listener.local_addr().unwrap();
    let mut client = TcpStream::connect(local).unwrap();
    poll.registry().register(&mut listener, SERVER, Interest::READABLE).unwrap();
    poll.registry().register(&mut client, CLIENT, Interest::WRITABLE).unwrap();

    // drive the non-blocking connect, then accept the loopback pair
    let mut server = None;
    while server.is_none() {
        poll.poll(&mut events, Some(Duration::from_secs(1))).unwrap();
        for ev in events.iter() {
            if ev.token() == SERVER && ev.is_readable() {
                server = Some(listener.accept().unwrap().0);
            }
        }
    }
    let mut server = server.unwrap();
    poll.registry().register(&mut server, ACCEPTED, Interest::READABLE).unwrap();

    // empty pipe: one timed poll, counting only ACCEPTED-readable events
    events.clear();
    poll.poll(&mut events, Some(Duration::from_millis(200))).unwrap();
    let ready = events.iter().filter(|e| e.token() == ACCEPTED && e.is_readable()).count();
    println!("empty-pipe: {}", ready);

    client.write_all(b"ping").unwrap();
    let mut ready = 0usize;
    while ready == 0 {
        events.clear();
        poll.poll(&mut events, Some(Duration::from_secs(1))).unwrap();
        ready += events.iter().filter(|e| e.token() == ACCEPTED && e.is_readable()).count();
    }
    println!("data-ready: 1");

    let mut buf = [0u8; 8];
    let len = server.read(&mut buf).unwrap();
    println!("{}", std::str::from_utf8(&buf[..len]).unwrap());
}
Output
empty-pipe: 0
data-ready: 1
ping

TypeScript v26.13.1

v26.13.1
import * as net from 'node:net';

// TS adds the types; the runtime event loop is still the multiplexor.
const server = net.createServer((conn: net.Socket) => {
  conn.on('data', (chunk: Buffer) => {
    console.log('data-ready: 1');
    console.log(chunk.toString().trim());
    conn.end();
    server.close();
  });
});
server.listen(0, '127.0.0.1', () => {
  const addr = server.address() as net.AddressInfo;
  const client = net.createConnection(addr.port, '127.0.0.1', () => {
    console.log('empty-pipe: 0');
    setTimeout(() => client.write('ping\n'), 20);
  });
});
Output
empty-pipe: 0
data-ready: 1
ping

Language differences

C: poll(2) as the portable facade (example), with the real split across platform backends — Linux epoll(7) (<sys/epoll.h>: epoll_create1/epoll_ctl/epoll_wait, optional edge triggering), BSD/macOS kqueue(2) (<sys/event.h>: kevent covers sockets, signals, and timers at once), Solaris event ports, Windows WSAPoll; select(2)/poll(2) re-send the whole fd array from user space per call and scan it in O(n), and the 1024 ceiling is exactly FD_SETSIZE.

C++: poll(2), same as C (example): the language has no multiplexing primitive of its own, and production code goes through Boost.Asio/libuv or raw epoll; asio's io_context is shaped like Io\Poll\Context — register handles, wait, take the ready set.

C#: Socket.Select is the standard library's only select-family call (example), scaling like select; the real poll-grade power lives inside the runtime — async sockets and SocketAsyncEventArgs are epoll on Linux underneath (what Kestrel rides for high concurrency), but that layer is not exposed to users.

Go: no polling API (example): the netpoller weaves epoll/kqueue into the runtime — a goroutine blocking on a read is parked, and the fd's readiness wakes it; the select statement multiplexes channels, not fds; readiness events are simply unreachable, which is the "hidden" school's design fork versus the "exposed" one (Io\Poll/Selector/mio).

Java: the NIO Selector (example): interest sets of SelectionKey.OP_READ/OP_WRITE plus select() returning the ready count, with epoll underneath on Linux — and Java 21's virtual threads stand on it too; concept-for-concept it matches Io\Poll (Context↔Selector, Watcher↔SelectionKey, Event↔interest set).

JavaScript: no polling API (example): the event loop (libuv) is epoll/kqueue underneath, but readiness is translated into callbacks like data/close; Node's net.Server on port 0 picks a random loopback port, so the example never touches a real network.

PHP: the 8.6 RFC poll_api (example): new Io\Poll\Context() picks the best backend automatically (getBackend() returns the Io\Poll\Backend enum — kqueue locally, epoll on Linux CI, hence the output asserts the type rather than naming a platform); add(StreamPollHandle, [Event::Read]) attaches an interest set, wait(?Time\Duration) returns an array of Watchers (empty = timeout), hasTriggered/getTriggeredEvents inspect the ready enums, and remove() detaches — set against stream_select (A25): the latter rewrites three arrays in place, caps at FD_SETSIZE 1024, and takes a microsecond timeout; the former is object-based, unbounded, and takes a Time\Duration directly; the target users are event-loop libraries like ReactPHP/AMPHP (release-page wording).

Python: selectors.DefaultSelector (example): automatically picks epoll/kqueue/devpoll/select, with register(key, EVENT_READ) + select(timeout) returning (key, events) lists — nearly isomorphic to Io\Poll's API shape; Python's standard library finished this same "select school → poll school" migration back in 2014 (3.4).

Rust: mio (example): epoll/kqueue/IOCP folded into one Poll type, with Token as the receipt tag from event back to registrant and Interest::READABLE declaring the interest set; the cross-platform abstraction at zero cost is Tokio's foundation, matching Io\Poll\Context piece by piece.

TypeScript: same as JS (example): types only decorate callback signatures ((chunk: Buffer) => void); "readiness" in the type system is an event parameter, not a return value — the event-driven answer to readiness polling at the type level.