andreasbuhr / cppcoro

A library of C++ coroutine abstractions for the coroutines TS
MIT License
364 stars 53 forks source link

Mutex unlock can potentially overflow the stack. Provide an async unlock to allow users to avoid the issue. #65

Open FunMiles opened 1 year ago

FunMiles commented 1 year ago

Reading the code of unlock for the async_mutex, my understanding is that if there's a long list of awaiters currently for the mutex, the mutex's holder's call to unlock will call resume() the first awaiter, whose unlock call will call resume() of the next awaiter and so on and so on, potentially running out of stack space. This potential situation might be avoided by use of an asynchronous unlock, by which co_await mutex.unlock() would suspend the lock holder, schedule it in some way for later resumption and make the first awaiter be resumed immediately by the symmetric return mechanism of await_suspend(...). Thus there would be chained calls to resume() consuming the stack.

andreasbuhr commented 11 months ago

I am unsure whether this problem actually exists.

The resume call you are referring to in https://github.com/andreasbuhr/cppcoro/blob/e86216e4fa6145f0184b5fef79230e9d4dc3aa77/lib/async_mutex.cpp#L85 is the last statement in that function. It seems to me that no destructors have to be called at the end of this function. I would guess the compiler can do tail-call optimization, thus not needing extra stack space for the call.

It would be very interesting to see whether one can create that stack overflow you are describing.