互斥锁
导入 <asco/sync/mutex.h>
头文件使用互斥锁。
锁的获取和释放使用 raii 类型封装,调用 .lock()
函数获取锁的保卫对象,保卫对象退出作用域后自动释放锁。
lock
协程返回类型为 future_inlie<mutex<T>::guard>
,需要 co_await
使其开始执行。
锁保卫对象与迭代器类似,通过重载的 *
运算符和重载的 ->
运算符访问锁内部的对象。
future_void foo() {
mutex<int> coro_local(muti);
auto g = co_await muti.lock();
*g = 5;
std::cout << "foo *g: " << *g << std::endl;
co_return {};
}
future<int> async_main() {
mutex<int> decl_local(muti);
future_void t;
{
auto g = co_await muti.lock();
t = foo();
std::cout << "*g: " << *g << std::endl;
}
co_await t;
co_return 0;
}
构造函数
mutex(const T&)
:将T
值拷贝进锁中。mutex(T&&)
:将T
值移动进锁中。template<typename... Args> mutex(Args &&...args)
:用完美转发在锁内部构造T
值。