-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAtomicValue.hx
70 lines (57 loc) · 1.42 KB
/
AtomicValue.hx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* SPDX-FileCopyrightText: © Vegard IT GmbH (https://vegardit.com) and contributors
* SPDX-FileContributor: Sebastian Thomschke, Vegard IT GmbH
* SPDX-License-Identifier: Apache-2.0
*/
package hx.concurrent.atomic;
import hx.concurrent.lock.RLock;
/**
* Value holder with thread-safe accessors.
*/
class AtomicValue<T> {
final _lock = new RLock();
/**
* <pre><code>
* >>> new AtomicValue(null).value == null
* >>> new AtomicValue(true).value == true
* >>> new AtomicValue("cat").value == "cat"
* </code></pre>
*/
public var value(get, never):T;
var _value:T;
function get_value():T {
_lock.acquire();
final result = _value;
_lock.release();
return result;
}
public function new(initialValue:T) {
this._value = initialValue;
}
/**
* <pre><code>
* >>> new AtomicValue("cat").getAndSet("dog") == "cat"
* </code></pre>
*/
public function getAndSet(value:T):T {
_lock.acquire();
final old = _value;
_value = value;
_lock.release();
return old;
}
public function set(value:T):Void {
_lock.acquire();
this._value = value;
_lock.release();
}
/**
* <pre><code>
* >>> new AtomicValue(true).toString() == "true"
* >>> new AtomicValue(false).toString() == "false"
* </code></pre>
*/
inline //
public function toString()
return Std.string(value);
}