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(); // 通知接收方不再有数据
});

spawn(function() use ($channel) {
    foreach ($channel as $value) {
        echo "Received: $value\n";
    }
    // foreach 在关闭并排空缓冲区后终止
    echo "Channel exhausted\n";
});

示例 #2 处理等待协程的关闭

<?php

use Async\Channel;

$channel = new Channel();

spawn(function() use ($channel) {
    try {
        $channel->send('data'); // 等待接收方
    } catch (\Async\ChannelException $e) {
        echo "Channel closed: {$e->getMessage()}\n";
    }
});

spawn(function() use ($channel) {
    delay(100); // 短暂延迟
    $channel->close(); // 以异常方式解除发送方的阻塞
});

参见