boostorg / boostorg/asio

Boost::Asio Asynchronous Mutex Implementation

Abierto
#418 2 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
C++
Estrellas
1.6k
Forks
485
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

I had a question about the following asynchronous mutex I am working on:
```
#include
#include
#include

class async_mutex {
public:
// Lock the mutex asynchronously
boost::asio::awaitable 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> 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.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.