Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

互斥锁

导入 <asco/sync/rwlock.h> 头文件使用读写锁。

锁的获取和释放使用 raii 类型封装,调用 .read().write() 函数获取锁的保卫对象,保卫对象退出作用域后自动释放锁。

readwrite 协程返回类型为 future_inlie<rwlock<T>::read_guard>future_inline<rwlock<T>::write_guard> ,需要 co_await 使其开始执行。

锁保卫对象与迭代器类似,通过重载的 * 运算符和重载的 -> 运算符访问锁内部的对象。

future<int> async_main() {
    rwlock<int> lk{10};
    {
        auto g1 = co_await lk.read();
        auto g2 = co_await lk.read();
        std::cout << *g1 << std::endl;
        std::cout << *g2 << std::endl;
        // auto g3 = co_await lk.write();  // cannot get it
    }
    {
        auto g = co_await lk.write();
        *g = 20;
        std::cout << *g << std::endl;
        // auto g1 = co_await lk.write();  // cannot get it
        // auto g1 = co_await lk.read();  // cannot get it
    }
    co_return 0;
}

构造函数

  • rwlock(const T&):将 T 值拷贝进锁中。
  • rwlock(T&&):将 T 值移动进锁中。
  • template<typename... Args> rwlock(Args &&...args):用完美转发在锁内部构造 T 值。