How to sync JavaScript callbacks?

The good news is that JavaScript is single threaded; this means that solutions will generally work well with “shared” variables, i.e. no mutex locks are required. If you want to serialize asynch tasks, followed by a completion callback you could use this helper function: function serializeTasks(arr, fn, done) { var current = 0; fn(function iterate() … Read more

Question about Java synchronized

No; synchronized only prevents multiple threads from simultaneously executing the method in the same instance. If you have n instances, there could be n threads, each executing the method in one of the instances. If you need to ensure that only one thread may execute the method across all instances, you should make the method … Read more

std::mutex performance compared to win32 CRITICAL_SECTION

Please see my updates at the end of the answer, the situation has dramatically changed since Visual Studio 2015. The original answer is below. I made a very simple test and according to my measurements the std::mutex is around 50-70x slower than CRITICAL_SECTION. std::mutex: 18140574us CRITICAL_SECTION: 296874us Edit: After some more tests it turned out … Read more

SynchronizationLockException on Monitor.Exit when using await

You can’t await a task inside a lock scope (which is syntactic sugar for Monitor.Enter and Monitor.Exit). Using a Monitor directly will fool the compiler but not the framework. async-await has no thread-affinity like a Monitor does. The code after the await will probably run in a different thread than the code before it. Which … Read more

When is a condition variable needed, isn’t a mutex enough?

Even though you can use them in the way you describe, mutexes weren’t designed for use as a notification/synchronization mechanism. They are meant to provide mutually exclusive access to a shared resource. Using mutexes to signal a condition is awkward and I suppose would look something like this (where Thread1 is signaled by Thread2): Thread1: … Read more