Drakim

Untitled

Jun 24th, 2016
544
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         function borrow() {
  2.  
  3.             // If we can't set busyFlag to "taken" then we have to wait for it to be free
  4.             while(!Memory.safeCompareExchange(busyFlag, 0, 1)) {
  5.  
  6.                 // Increase the busyQueue by one and use this as our queue number
  7.                 var qnr = Memory.safeAdd(busyQueue, 1) + 1;
  8.  
  9.                 // If our queue number is over 100 we warp around
  10.                 if(qnr > 100) {
  11.                     // Attempt to set the queue number back by 100. This might fail due to a race condition if another thread
  12.                     // has advanced the busyQueue right after us. If that is the case, it's up to that thread to adjust it back
  13.                     Memory.safeCompareExchange(busyQueue, qnr, qnr-100);
  14.  
  15.                     // Either way, our queue number is warped around
  16.                     qnr -= 100;
  17.                 }
  18.  
  19.                 // Wait until we are woken with busyQueueAction set to our queue number
  20.                 while( !Memory.wait(busyQueueAction, qnr) ) {}
  21.  
  22.                 // If we can set the busyFlag to "taken" from the "transfer" state we are done
  23.                 if(Memory.safeCompareExchange(busyFlag, 2, 1) {
  24.                     break;
  25.                 }
  26.  
  27.                 // A race condition got us, we start over instead
  28.             }
  29.  
  30.         }
  31.  
  32.         function release() {
  33.  
  34.             // Set the busyFlag to the "transfer" state
  35.             Memory.safeWrite(busyFlag, 2);
  36.  
  37.             // Advance the busyQueueAction by one
  38.             var ticket = Memory.safeAdd(busyQueueAction, 1) + 1;
  39.  
  40.             // If the ticket is over 100 we warp around
  41.             if(ticket > 100) { Memory.safeSub(busyQueueAction, 100); }
  42.  
  43.             // Wake all the waiting threads
  44.             var woken = Memory.wake(busyQueueAction);
  45.  
  46.             // Potential race condition if a thread borrow call invokes wait() now
  47.  
  48.             // If nobody is listening, free up the busyflag
  49.             if(woken == 0) {Memory.safeWrite(busyFlag, 0);}
  50.  
  51.             // Wake any thread that might be the victim of a race condition
  52.             Memory.wake(busyQueueAction);
  53.  
  54.         }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×