Last active
May 12, 2024 05:24
-
-
Save dfkaye/94e6abfb9beb91d325a407ce13da53ad to your computer and use it in GitHub Desktop.
chapter 8 Data oriented programming non-blocking Atom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 11 May 2024 | |
// chapter 8 Data oriented programming | |
// atomic value swap alg | |
function Atom (state) { | |
return { | |
state, | |
atomicCompareAndSet(current, previous, next) { | |
return current === previous ? (state = next, true) : false; | |
}, | |
get() { | |
return state; | |
}, | |
set(next) { | |
state = next; | |
}, | |
// should make this non-blocking somehow | |
swap(f) { | |
while(true) { | |
var previous = state; | |
var next = f(previous); | |
if (!this.atomicCompareAndSet(state, | |
previous, | |
next)) { | |
continue; | |
} | |
return next; | |
} | |
} | |
}; | |
} | |
var a = Atom(9); | |
a.swap(function (x) { | |
return x// = x + 1; | |
}); | |
a.get() | |
console.warn(a); | |
// function atomicCompareAndSet(state, previous, next) { | |
// return state === previous ? this.state = next && true : false; | |
// } | |
function Value(...o) { | |
var v = o.filter(x => Object(x).valueOf() === x)[0] | |
return { | |
value: (...u) => u.length ? v = u[0] : v, | |
// should make this non-blocking somehow | |
swap(f) { | |
while(true) { | |
var previous = v; | |
var next = f(previous); | |
if (v === previous /*&& Object(next).valueOf() === next*/) { return v = next; } | |
} | |
} | |
}; | |
} | |
var v = Value(0); | |
function next() { | |
console.log('current:', v.value()) | |
return v.swap(x => NaN) | |
} | |
next() | |
//v.value(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment