views:

36

answers:

2

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?

+1  A: 

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--;
    }
 }
}
Sanjay Manohar
I can do a static variable no problem, my concern wasn't I wasn't sure that ++ _Was_ an atomic operation. Do you know if this is the case for JS? If that's true, this problem is (I believe), solvable. Your function looks like it does it correctly, actually.
Michael
+1  A: 

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.

Brian Campbell
I'm actually utilizing web workers, but that's beside the point. My worry is if the onMessage function gets called twice. While it may be "single threaded", won't it thread the two calls to it intermittently, if they end up running in the same time period?
Michael
@Michael What resource are you trying to protect access to with your mutual exclusion?
Brian Campbell
Say I've got some global array, and I need to store something in it, and return the index of the item stored. Normally, I'd check the length, push it into the array, and return the length of the array. But if the second thread (that was called due to an asynchronous event) gets threaded between the getting of the array length, and pushing the new value onto the array, and does the same thing itself, the first function will return the wrong index.
Michael