Channel::__construct

(PHP 8.6+, True Async 1.0)

public Channel::__construct(int $capacity = 0)

코루틴 간 데이터 전달을 위한 새로운 채널을 생성합니다.

채널은 코루틴이 안전하게 데이터를 교환할 수 있게 하는 동기화 프리미티브입니다. 채널의 동작은 $capacity 매개변수에 따라 달라집니다:

매개변수

capacity
채널 내부 버퍼의 용량. 0 — 랑데부 채널 (기본값), send는 receive가 올 때까지 블로킹. 양수 — 버퍼 크기.

예제

예제 #1 랑데부 채널 (버퍼 없음)

<?php

use Async\Channel;

$channel = new Channel(); // capacity = 0

spawn(function() use ($channel) {
    $channel->send('hello'); // suspends until someone calls recv()
    echo "Sent\n";
});

spawn(function() use ($channel) {
    $value = $channel->recv(); // receives 'hello', unblocks the sender
    echo "Received: $value\n";
});

예제 #2 버퍼 채널

<?php

use Async\Channel;

$channel = new Channel(3); // buffer for 3 elements

spawn(function() use ($channel) {
    $channel->send(1); // does not block — buffer is empty
    $channel->send(2); // does not block — space available
    $channel->send(3); // does not block — last slot
    $channel->send(4); // suspends — buffer is full
});

같이 보기