asio
asio copied to clipboard
Boost::Asio Asynchronous Mutex Implementation
I had a question about the following asynchronous mutex I am working on:
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <memory>
class async_mutex {
public:
// Lock the mutex asynchronously
boost::asio::awaitable<void> async_lock() {
// Define the lock_awaiter object that will handle suspension and resumption
class lock_awaiter {
public:
lock_awaiter(async_mutex& mutex) : m_mutex(mutex) {}
// Check if the mutex is locked
bool await_ready() const noexcept {
return m_mutex.m_mutex.try_lock();
}
// Suspend the coroutine and add it to the list of waiters
void await_suspend(std::coroutine_handle<> coroutine) {
m_mutex.m_waiters.emplace_back(coroutine);
}
// Unused, just to match the coroutine_traits definition
void await_resume() noexcept {}
private:
async_mutex& m_mutex;
};
// Return the lock_awaiter object
return lock_awaiter(*this);
}
// Unlock the mutex and resume the first waiting coroutine
void unlock() {
// Acquire a lock on the internal mutex to protect access to m_waiters
boost::mutex::scoped_lock lock(m_mutex);
// If there are waiting coroutines, resume the first one in the queue
if (!m_waiters.empty()) {
auto coroutine = m_waiters.front();
m_waiters.pop_front();
coroutine.resume();
} else {
m_mutex.unlock();
}
}
private:
// Deque of coroutines waiting for the mutex to be released
std::deque<std::coroutine_handle<>> m_waiters;
// Internal mutex used to protect access to m_waiters
boost::mutex m_mutex;
};
The goal of this is to be able to use mutexes on an io_ctx that uses multiple threads that may have to contend for shared resources. I think the above is correct. My primary concern is that in my await_ready() try_lock's behavior is technically undefined for a thread that already owns the mutex. In a scenario where say Thread1 is running async(f1()) who owns the mutex and suspends for some other reason, if Thread1 upon suspensions picks up async(f2()) which tries to acquire the mutex this could result in undefined behavior.