aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/Common/Concurrent.cs
blob: d8d9a6caf243819443201ff57dda31c9f60c045f (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace QtVsTools
{
    /// <summary>
    /// Base class of objects requiring thread-safety features
    /// </summary>
    ///
    [DataContract]
    public abstract class Concurrent<TSubClass>
        where TSubClass : Concurrent<TSubClass>
    {
        // Shared static critical section used by non-resource methods (like ThreadSafeInit).
        protected static object StaticCriticalSection { get; } = new();

        // Per-instance critical section to lock per instance rather than global.
        protected object CriticalSection { get; } = new();

        protected static ConcurrentDictionary<string, Resource> Resources { get; } = new();

        protected sealed class Resource
        {
            public object SyncRoot { get; } = new();
            public bool IsLocked { get; set; }
        }

        // Optionally remove the resource from the dictionary entirely.
        protected static void Free(string resourceName)
        {
            Resources.TryRemove(resourceName, out _);
        }

        protected static bool Get(string resourceName, int timeout = -1)
        {
            var resource = Resources.GetOrAdd(resourceName, _ => new Resource());

            lock (resource.SyncRoot) {
                if (timeout < 0) {
                    // Infinite wait
                    while (resource.IsLocked)
                        Monitor.Wait(resource.SyncRoot);

                    resource.IsLocked = true;
                    return true;
                }

                // Timed wait
                var startTime = Environment.TickCount;
                while (resource.IsLocked) {
                    var elapsed = Environment.TickCount - startTime;
                    // Guard against overflow
                    if (elapsed < 0)
                        elapsed = int.MaxValue;

                    var remaining = timeout - elapsed;
                    if (remaining <= 0 || !Monitor.Wait(resource.SyncRoot, remaining))
                        return false; // Timed out
                }

                resource.IsLocked = true;
                return true;
            }
        }

        protected static async Task<bool> GetAsync(string resourceName, int timeout = -1)
        {
            return await Task.Run(() => Get(resourceName, timeout));
        }

        protected static void Release(string resourceName)
        {
            if (!Resources.TryGetValue(resourceName, out var resource))
                return;

            lock (resource.SyncRoot) {
                if (!resource.IsLocked)
                    return;
                resource.IsLocked = false;
                Monitor.Pulse(resource.SyncRoot);
            }
        }

        protected T ThreadSafeInit<T>(Func<T> getValue, Action init)
            where T : class
        {
            return StaticThreadSafeInit(getValue, init, this);
        }

        protected static T StaticThreadSafeInit<T>(
                Func<T> getValue,
                Action init,
                Concurrent<TSubClass> instance = null)
            where T : class
        {
            // prevent global lock at every call
            var value = getValue();
            if (value != null)
                return value;

            lock (instance?.CriticalSection ?? StaticCriticalSection) {
                // prevent race conditions
                value = getValue();
                if (value != null)
                    return value;
                init();
                value = getValue();
                return value;
            }
        }

        protected void EnterCriticalSection()
        {
            EnterStaticCriticalSection(this);
        }

        protected bool TryEnterCriticalSection()
        {
            return TryEnterStaticCriticalSection(this);
        }

        protected static void EnterStaticCriticalSection(Concurrent<TSubClass> instance = null)
        {
            Monitor.Enter(instance?.CriticalSection ?? StaticCriticalSection);
        }

        protected static bool TryEnterStaticCriticalSection(Concurrent<TSubClass> instance = null)
        {
            return Monitor.TryEnter(instance?.CriticalSection ?? StaticCriticalSection);
        }

        protected void LeaveCriticalSection()
        {
            LeaveStaticCriticalSection(this);
        }

        protected static void LeaveStaticCriticalSection(Concurrent<TSubClass> instance = null)
        {
            if (Monitor.IsEntered(instance?.CriticalSection ?? StaticCriticalSection))
                Monitor.Exit(instance?.CriticalSection ?? StaticCriticalSection);
        }

        protected void AbortCriticalSection()
        {
            AbortStaticCriticalSection(this);
        }

        protected static void AbortStaticCriticalSection(Concurrent<TSubClass> instance = null)
        {
            while (Monitor.IsEntered(instance?.CriticalSection ?? StaticCriticalSection))
                Monitor.Exit(instance?.CriticalSection ?? StaticCriticalSection);
        }

        protected void ThreadSafe(Action action)
        {
            StaticThreadSafe(action, this);
        }

        protected static void StaticThreadSafe(Action action, Concurrent<TSubClass> instance = null)
        {
            lock (instance?.CriticalSection ?? StaticCriticalSection) {
                action();
            }
        }

        protected T ThreadSafe<T>(Func<T> func)
        {
            return StaticThreadSafe(func, this);
        }

        protected static T StaticThreadSafe<T>(Func<T> func, Concurrent<TSubClass> instance = null)
        {
            lock (instance?.CriticalSection ?? StaticCriticalSection) {
                return func();
            }
        }

        protected bool Atomic(Func<bool> test, Action action)
        {
            return StaticAtomic(test, action, instance: this);
        }

        protected bool Atomic(Func<bool> test, Action action, Action actionElse)
        {
            return StaticAtomic(test, action, actionElse, this);
        }

        protected static bool StaticAtomic(
            Func<bool> test,
            Action action,
            Action actionElse = null,
            Concurrent<TSubClass> instance = null)
        {
            bool success;
            lock (instance?.CriticalSection ?? StaticCriticalSection) {
                success = test();
                if (success)
                    action();
                else
                    actionElse?.Invoke();
            }
            return success;
        }
    }

    /// <summary>
    /// Base class of objects requiring thread-safety features
    /// Sub-classes will share the same static critical section
    /// </summary>
    ///
    [DataContract]
    public class Concurrent : Concurrent<Concurrent>
    {
    }

    /// <summary>
    /// Simplify use of synchronization features in classes that are not Concurrent-based.
    /// </summary>
    ///
    public sealed class Synchronized : Concurrent<Synchronized>
    {
        private Synchronized() { }

        public static new bool Atomic(Func<bool> test, Action action)
        {
            return StaticAtomic(test, action);
        }

        public static new bool Atomic(Func<bool> test, Action action, Action actionElse)
        {
            return StaticAtomic(test, action, actionElse);
        }

        public static new void ThreadSafe(Action action)
        {
            StaticThreadSafe(action);
        }

        public static new T ThreadSafe<T>(Func<T> func)
        {
            return StaticThreadSafe(func);
        }

        public static new void Free(string resourceName)
        {
            Concurrent.Free(resourceName);
        }

        public static new bool Get(string resourceName, int timeout = -1)
        {
            return Concurrent.Get(resourceName, timeout);
        }

        public static new Task<bool> GetAsync(string resourceName, int timeout = -1)
        {
            return Concurrent.GetAsync(resourceName, timeout);
        }

        public static new void Release(string resourceName)
        {
            Concurrent.Release(resourceName);
        }

        // Expose the base critical section if needed
        public static new object StaticCriticalSection => Concurrent.StaticCriticalSection;
    }

    /// <summary>
    /// Allows exclusive access to a wrapped variable. Reading access is always allowed. Concurrent
    /// write requests are protected by instance-based "critical sections." Once a thread sets a
    /// non-default value, it effectively 'holds' it until it sets it back to default.
    /// </summary>
    /// <typeparam name="T">Type of wrapped variable</typeparam>
    ///
    [DataContract]
    public class Exclusive<T> : Concurrent
    {
        private T value;

        public void Set(T newValue)
        {
            EnterCriticalSection();
            if (IsNull(value) && !IsNull(newValue)) {
                // Acquiring
                value = newValue;

            } else if (!IsNull(value) && !IsNull(newValue)) {
                // Already held, update in place
                value = newValue;
                LeaveCriticalSection();

            } else if (!IsNull(value) && IsNull(newValue)) {
                // Releasing
                value = default;
                LeaveCriticalSection();
                // This class uses nested calls, so we call LeaveCriticalSection() once more
                LeaveCriticalSection();

            } else {
                // Edge case: was null, setting null => no change
                LeaveCriticalSection();
            }
        }

        private static readonly EqualityComparer<T> EqualityComparer = EqualityComparer<T>.Default;
        private static bool IsNull(T val) => EqualityComparer.Equals(val, default);

        // Sets value to default => releases one level of lock
        // plus the additional "extra" lock if it was currently held.
        public void Release()
        {
            Set(default);
        }

        public static implicit operator T(Exclusive<T> instance)
        {
            return instance.value;
        }
    }
}