From 3ecd8511f2401d61b512c1f9fad1e6f6eb5676e5 Mon Sep 17 00:00:00 2001 From: Aidan Lee Date: Fri, 4 Jul 2025 20:01:45 +0100 Subject: [PATCH] emulate atomic object for hxcpp --- std/cpp/_std/haxe/atomic/AtomicObject.hx | 59 +++++++++++++++++++ std/haxe/atomic/AtomicObject.hx | 4 +- .../unitstd/haxe/atomic/AtomicObject.unit.hx | 2 +- 3 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 std/cpp/_std/haxe/atomic/AtomicObject.hx diff --git a/std/cpp/_std/haxe/atomic/AtomicObject.hx b/std/cpp/_std/haxe/atomic/AtomicObject.hx new file mode 100644 index 00000000000..a8c129d1a6f --- /dev/null +++ b/std/cpp/_std/haxe/atomic/AtomicObject.hx @@ -0,0 +1,59 @@ +package haxe.atomic; + +private class AtomicObjectImpl { + public final lock : sys.thread.Mutex; + + public var obj : T; + + public function new(obj) { + this.lock = new sys.thread.Mutex(); + this.obj = obj; + } +} + +abstract AtomicObject(AtomicObjectImpl) { + public function new(value:T) { + this = new AtomicObjectImpl(value); + } + + public function compareExchange(expected:T, replacement:T):T { + this.lock.acquire(); + return if (this.obj == expected) { + final current = this.obj; + this.obj = replacement; + this.lock.release(); + + current; + } else { + final current = this.obj; + this.lock.release(); + + current; + } + } + + public function exchange(value:T):T { + this.lock.acquire(); + final current = this.obj; + this.obj = value; + this.lock.release(); + + return current; + } + + public function load():T { + this.lock.acquire(); + final current = this.obj; + this.lock.release(); + + return current; + } + + public function store(value:T):T { + this.lock.acquire(); + this.obj = value; + this.lock.release(); + + return value; + } +} \ No newline at end of file diff --git a/std/haxe/atomic/AtomicObject.hx b/std/haxe/atomic/AtomicObject.hx index 01b959b2480..8c8c051b332 100644 --- a/std/haxe/atomic/AtomicObject.hx +++ b/std/haxe/atomic/AtomicObject.hx @@ -4,8 +4,8 @@ package haxe.atomic; #error "This target does not support atomic operations." #end -#if (js || cpp) -#error "JavaScript and Hxcpp do not support AtomicObject" +#if js +#error "JavaScript does not support AtomicObject" #end /** diff --git a/tests/unit/src/unitstd/haxe/atomic/AtomicObject.unit.hx b/tests/unit/src/unitstd/haxe/atomic/AtomicObject.unit.hx index 7f95e195f7f..8b5183e8604 100644 --- a/tests/unit/src/unitstd/haxe/atomic/AtomicObject.unit.hx +++ b/tests/unit/src/unitstd/haxe/atomic/AtomicObject.unit.hx @@ -1,4 +1,4 @@ -#if (target.atomics && !(js || cpp)) +#if (target.atomics && !js) var a = new haxe.atomic.AtomicObject("Hey World!"); a.load() == "Hey World!";