Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual Exclusion for N Asynchronous Threads

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?

like image 676
Michael Avatar asked Sep 12 '10 02:09

Michael


3 Answers

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--;
    }
 }
}
like image 154
Sanjay Manohar Avatar answered Oct 24 '22 00:10

Sanjay Manohar


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.

like image 30
Brian Campbell Avatar answered Oct 24 '22 00:10

Brian Campbell


Can be single threaded but sometimes there is a problem when some user actions are running multiple threads that we would like to avoid (for ex. AJAX requests). If we would like to make a semaphore we can use a global variable. Anyways, I'm sure it shouldn't be done this way - I just don't know any better solution as I'm not involved in JS so much.

Hope it'll help you in some simple situations:

<html>

 <head>
  <script type="text/javascript">
        var magic_global;
        magic_global = true;

        function magic_switch() {
                magic_global = !magic_global;
        }
  </script>
 </head>

 <body>
        <a href="#" onclick="magic_switch();">switch Magic</a>
        <a href="#" onclick="alert(magic_global);">show the Magic</a>
 </body>

</html>
like image 1
Pawel Avatar answered Oct 23 '22 23:10

Pawel