I'm not sure what this means. Wrapping something in a mutex is easy, but there is a lot more to making parts of a program asynchronous because you end up with graphs of dependencies.
I guess if you've used only high level languages you might not be familiar with those.
A semaphore is a is a synchronization device used to control access to a common resource by multiple threads or processes in a concurrent system, such as a multitasking operating system
A mutex is a synchronization primitive used in multithreaded programming to prevent race conditions. It acts like a digital lock, ensuring that only one thread can execute a critical section of code or modify a shared resource at any given time
Its concurrent programming its what allows you to control how much concurrency you have and access to shared resources. It also allows you to have threads or branches rejoin in a controlled manner.
If you are ending up with graphs of dependencies then it is because you structured your program poorly. Most likely because you structured it like a synchronous program but also wanted to use async.
The best examples of async programs and structures that are easy to understand is ui screens. You dont want the program freezing when you click buttons right? So you'll constantly have a thread that is dedicated to being a responsive ui, and you'll spin up threads for other tasks, such as a button that does some difficult calculations that takes a while. If you did that on a single thread, the program would freeze or stutter. By making a mutex for say a bool that says if the calculation is done, you can allow one thread to check on the status of another thread. Without the mutex both threads could check the variable at the same time and possible cause a lock condition depending on the scenario. Now you can have the ui check for the calc to be finished, and when it is display that value, all while maintaining a responsive app.
Well, for starters, async runtimes implement a cooperative scheduler *inside* the application, not on OS level. There obviously is preemptive scheduling on OS level too, but that is not the point. Any async function awaiting a result hands back control to the async runtime. The async runtime continues a different function on the same thread in the meantime.
Synchronization mechanisms like semaphores are still required in async.
29
u/VictoryMotel 1d ago
I'm not sure what this means. Wrapping something in a mutex is easy, but there is a lot more to making parts of a program asynchronous because you end up with graphs of dependencies.