I've got an asynchronous application, meaning that at any given time there can be N events. Is there a known algorithm for doing mutual exclusion for N threads, without hardcoding each thread to have an ID?
I don't think Javascript per se has object locking - because Javascript is basically single-threaded. You might be able to find a library or implementation that runs several threads of Javascript code - but are they all running in the same variable-space? They will need to communicate with each other somehow.
Assuming your multiple threads can share a static mutex
variable somehow, and insofar as you assume '++
' is considered an atomic operation for the system that is doing your threading, how about this?
int mutex = 0;
mutuallyExclusiveOperation(){
succeed=false;
while(!succeed){
while(mutex>0){ sleep(); }
m=mutex++; //"Simultaneously" read and increment
if(m>0)mutex--;
else{
doMutuallyExclusiveThing();
succeed=true;
mutex--;
}
}
}
JavaScript is generally single threaded, so you never have two pieces of code modifying the same data at the same time. You can use multiple threads in modern browsers using Web Workers, but they can only communicate by passing messages, not sharing memory, so you don't need to worry about mutual exclusion if you're using web workers.