1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.concurrency.Locker;
13 
14 import hunt.Exceptions;
15 import hunt.util.Common;
16 
17 /**
18  * <p>
19  * This is a lock designed to protect VERY short sections of critical code.
20  * Threads attempting to take the lock will wait until the lock is available,
21  * thus it is important that the code protected by this lock is extremely simple
22  * and non blocking.
23  * </p>
24  *
25  * <pre>
26  * try (SpinLock.Lock lock = locker.lock()) {
27  * 	// something very quick and non blocking
28  * }
29  * </pre>
30  */
31 class Locker {
32     private enum bool SPIN = true; 
33 
34     private  bool _spin;
35     // private  ReentrantLock _lock = new ReentrantLock();
36     // private  AtomicReference!(Thread) _spinLockState = new AtomicReference<>(null);
37     private  Lock _unlock; // = new Lock();
38 
39     this() {
40         this(SPIN);
41     }
42 
43     this(bool spin) {
44         _unlock = new Lock();
45         this._spin = spin;
46     }
47 
48     Lock lock() {
49         // if (_spin)
50         //     spinLock();
51         // else
52         //     concLock();
53         return _unlock;
54     }
55 
56     // private void spinLock() {
57     //     Thread current = Thread.currentThread();
58     //     while (true) {
59     //         // Using test-and-test-and-set for better performance.
60     //         Thread locker = _spinLockState.get();
61     //         if (locker !is null || !_spinLockState.compareAndSet(null, current)) {
62     //             if (locker == current)
63     //                 throw new IllegalStateException("Locker is not reentrant");
64     //             continue;
65     //         }
66     //         return;
67     //     }
68     // }
69 
70     private void concLock() {
71         // if (_lock.isHeldByCurrentThread())
72         //     throw new IllegalStateException("Locker is not reentrant");
73         // _lock.lock();
74     }
75 
76     bool isLocked() {
77         // if (_spin)
78         //     return _spinLockState.get() !is null;
79         // else
80         //     return _lock.isLocked();
81         // implementationMissing();
82         return false;
83     }
84 
85     class Lock : AutoCloseable {
86         override
87         void close() {
88             // if (_spin)
89             //     _spinLockState.set(null);
90             // else
91             //     _lock.unlock();
92         }
93     }
94 
95     // void lock(Action0 action0) {
96     //     try (Lock lock = lock()) {
97     //         action0.call();
98     //     }
99     // }
100 
101     // !(T) T lock(Func0!(T) func0) {
102     //     try (Lock lock = lock()) {
103     //         return func0.call();
104     //     }
105     // }
106 }