Lab5c 实验解析
tinyCoroLab5c 实验解析
git clone https://github.com/sakurs2/tinyCoro📖lab5c 任务参考实现
🧑💻Task #1 - 实现 channel
class channel_base
{
public:
~channel_base() noexcept { assert(part_closed() && "detected channel destruct with no_close state"); }
// 关闭 channel
auto close() noexcept -> void
{
// 将 channel 状态置为部分关闭
std::atomic_ref<uint8_t>(m_close_state).store(part_close, std::memory_order_release);
m_producer_cv.notify_all(); // 唤醒所有生产者协程
m_consumer_cv.notify_all(); // 唤醒所有消费者协程
}
protected:
// 检查 channel 是否处于完全关闭状态,原子操作
inline auto complete_closed_atomic() noexcept -> bool
{
return std::atomic_ref<uint8_t>(m_close_state).load(std::memory_order_acquire) <= complete_close;
}
// 检查 channel 是否处于部分关闭状态,原子操作
inline auto part_closed_atomic() noexcept -> bool
{
return std::atomic_ref<uint8_t>(m_close_state).load(std::memory_order_acquire) <= part_close;
}
// 检查 channel 是否处于部分关闭状态,非原子操作
inline auto part_closed() noexcept -> bool { return m_close_state <= part_close; }
protected:
// 表示 channel 已完全关闭,即调用了 close 且全部元素均被消费
inline static constexpr uint8_t complete_close = 0;
// 表示 channel 已部分关闭,即调用了 close 但仍有元素未消费
inline static constexpr uint8_t part_close = 1;
// 表示 channel 未关闭
inline static constexpr uint8_t no_close = 2;
mutex m_mtx; // 用于条件变量的锁
condition_variable m_producer_cv; // 生产者条件变量
condition_variable m_consumer_cv; // 消费者条件变量
// 保存当前 channel 状态
alignas(std::atomic_ref<uint8_t>::required_alignment) uint8_t m_close_state{no_close};
};实验总结
Last updated