Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function borrow() {
- // If we can't set busyFlag to "taken" then we have to wait for it to be free
- while(!Memory.safeCompareExchange(busyFlag, 0, 1)) {
- // Increase the busyQueue by one and use this as our queue number
- var qnr = Memory.safeAdd(busyQueue, 1) + 1;
- // If our queue number is over 100 we warp around
- if(qnr > 100) {
- // Attempt to set the queue number back by 100. This might fail due to a race condition if another thread
- // has advanced the busyQueue right after us. If that is the case, it's up to that thread to adjust it back
- Memory.safeCompareExchange(busyQueue, qnr, qnr-100);
- // Either way, our queue number is warped around
- qnr -= 100;
- }
- // Wait until we are woken with busyQueueAction set to our queue number
- while( !Memory.wait(busyQueueAction, qnr) ) {}
- // If we can set the busyFlag to "taken" from the "transfer" state we are done
- if(Memory.safeCompareExchange(busyFlag, 2, 1) {
- break;
- }
- // A race condition got us, we start over instead
- }
- }
- function release() {
- // Set the busyFlag to the "transfer" state
- Memory.safeWrite(busyFlag, 2);
- // Advance the busyQueueAction by one
- var ticket = Memory.safeAdd(busyQueueAction, 1) + 1;
- // If the ticket is over 100 we warp around
- if(ticket > 100) { Memory.safeSub(busyQueueAction, 100); }
- // Wake all the waiting threads
- var woken = Memory.wake(busyQueueAction);
- // Potential race condition if a thread borrow call invokes wait() now
- // If nobody is listening, free up the busyflag
- if(woken == 0) {Memory.safeWrite(busyFlag, 0);}
- // Wake any thread that might be the victim of a race condition
- Memory.wake(busyQueueAction);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement