async-book
async-book copied to clipboard
Managing shared state chapter - ideas
I just wanted to share some experience about this topic that is on the TODO list for the book. I don't feel confident enough to write this topic myself, but would like to contribute some ideas.
- Something I'm confused about still is using references in async/await. I read blog posts from withoutboats explaining that we can use references, but in practice I end up with alot of Rc<RefCell<_>> on self.
There is 2 topics that I see important to mention:
-
The need for synchronization (dope, well as in thread synchronization), in async code. The compiler currently isn't as well equipped for async as it is for multi-threading, but similar issues arise. Where the compiler won't let you access data from multiple threads without using a locking mechanism, RefCell will cause runtime issues when borrowed twice. In multi-threading blocking the thread waiting for a lock will (with the exception of deadlocks) kind of automatically solve the synchronization problem, but in async code you can't block the thread. You can't just
await
the borrow being released. Enter critical sections. I find myself writing code so that there are no yield points (awaits) between borrowing and releasing a RefCell. That way I can guarantee there will be no double borrow. -
Other synchronization issues: What if two unrelated paths through the program require that a runs before b. I could store a future somewhere, but I should not poll it from 2 different paths. There is no way to ask a future "are you ready" without consuming it. I could set a boolean saying that something has resolved, but I cannot await a boolean... I would have to make a custom future that returns not ready based on that boolean? I'm a bit confused about how to deal with this... There most certainly are ways, but finding something generic with not to much boilerplate and overhead?
Hope that this helps launching some discussion and eventual writing of the chapter...
ps: futures-locks look interesting as well
desperately waiting for this chapter
Maybe, make an AsyncRefCell?
It seems like you're describing Actix exactly. The Actix Book explanations for SyncArbiter
and Arbiter
match these concurrency examples, afaict.
In my case, I'm working on using Actix in the Torchbear library and later within its scripting environment for concurrent network processing.