Channel::close

(PHP 8.6+, True Async 1.0)

public Channel::close(): void

채널을 닫습니다. 닫은 후:

이미 닫힌 채널에 대해 close()를 다시 호출해도 오류가 발생하지 않습니다.

예제

예제 #1 데이터 전송 후 채널 닫기

<?php

use Async\Channel;

$channel = new Channel(10);

spawn(function() use ($channel) {
    for ($i = 0; $i < 5; $i++) {
        $channel->send($i);
    }
    $channel->close(); // signal to the receiver that no more data will come
});

spawn(function() use ($channel) {
    foreach ($channel as $value) {
        echo "Received: $value\n";
    }
    // foreach terminates after closing and draining the buffer
    echo "Channel exhausted\n";
});

예제 #2 대기 중인 코루틴의 닫기 처리

<?php

use Async\Channel;

$channel = new Channel();

spawn(function() use ($channel) {
    try {
        $channel->send('data'); // waiting for a receiver
    } catch (\Async\ChannelException $e) {
        echo "Channel closed: {$e->getMessage()}\n";
    }
});

spawn(function() use ($channel) {
    delay(100); // short delay
    $channel->close(); // unblocks the sender with an exception
});

같이 보기