1 // =================================
 2 // Copyright (c) 2024 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 using System;
 7 using System.Concepts;
 8 
 9 namespace System.Threading
10 {
11     public class Mutex
12     {
13         public Mutex() : nativeHandle(RtmAllocateMutex())
14         {
15         }
16         public ~Mutex()
17         {
18             if (nativeHandle != null)
19             {
20                 RtmFreeMutex(nativeHandle);
21             }
22         }
23         suppress Mutex(const Mutex&);
24         suppress void operator=(Mutex&);
25         suppress Mutex(Mutex&&);
26         suppress void operator=(Mutex&&);
27         public void Lock()
28         {
29             RtmLockMutex(nativeHandle);
30         }
31         public void Unlock()
32         {
33             RtmUnlockMutex(nativeHandle);
34         }
35         private void* nativeHandle;
36     }
37 
38     public class RecursiveMutex
39     {
40         public RecursiveMutex() : nativeHandle(RtmAllocateRecursiveMutex())
41         {
42         }
43         public ~RecursiveMutex()
44         {
45             if (nativeHandle != null)
46             {
47                 RtmFreeRecursiveMutex(nativeHandle);
48             }
49         }
50         suppress RecursiveMutex(const RecursiveMutex&);
51         suppress void operator=(RecursiveMutex&);
52         suppress RecursiveMutex(RecursiveMutex&&);
53         suppress void operator=(RecursiveMutex&&);
54         public void Lock()
55         {
56             RtmLockRecursiveMutex(nativeHandle);
57         }
58         public void Unlock()
59         {
60             RtmUnlockRecursiveMutex(nativeHandle);
61         }
62         public void* NativeHandle() const
63         {
64             return nativeHandle;
65         }
66         private void* nativeHandle;
67     }
68 
69     public class LockGuard<Mtx> where Mtx is Lockable
70     {
71         private typedef LockGuard<Mtx> Self;
72         public LockGuard(Mtx& mtx_) : mtx(mtx_)
73         {
74             mtx.Lock();
75         }
76         public ~LockGuard()
77         {
78             mtx.Unlock();
79         }
80         suppress LockGuard(const Self&);
81         suppress void operator=(const Self&);
82         suppress LockGuard(Self&&);
83         suppress void operator=(Self&&);
84         private Mtx& mtx;
85     }