Mercurial > pub > ImplabNet
annotate Implab/Parallels/SharedLock.cs @ 134:04d4c92d0f28 v2
Improved logging
| author | cin |
|---|---|
| date | Wed, 11 Feb 2015 02:12:15 +0300 |
| parents | 671f60cd0250 |
| children | e9e7940c7d98 |
| rev | line source |
|---|---|
| 129 | 1 using System; |
| 2 using System.Threading; | |
| 3 using System.Diagnostics; | |
| 4 | |
| 5 namespace Implab.Parallels { | |
| 6 /// <summary> | |
| 7 /// Implements a lightweight mechanism to aquire a shared or an exclusive lock. | |
| 8 /// </summary> | |
| 9 public class SharedLock { | |
| 10 readonly object m_lock = new object(); | |
| 11 int m_locks; | |
| 12 bool m_exclusive; | |
| 13 | |
| 14 public bool LockExclusive(int timeout) { | |
| 15 lock (m_lock) { | |
| 16 if (m_locks > 0 && !Monitor.Wait(m_lock, timeout)) | |
| 17 return false; | |
| 18 m_exclusive = true; | |
| 19 m_locks = 1; | |
|
130
671f60cd0250
fixed Resove method bug when calling it on already cancelled promise
cin
parents:
129
diff
changeset
|
20 return true; |
| 129 | 21 } |
| 22 } | |
| 23 | |
| 24 public void LockExclusive() { | |
| 25 LockExclusive(-1); | |
| 26 } | |
| 27 | |
| 28 public bool LockShared(int timeout) { | |
| 29 lock (m_lock) { | |
| 30 if (!m_exclusive) { | |
| 31 m_locks++; | |
| 32 return true; | |
| 33 } | |
| 34 | |
|
130
671f60cd0250
fixed Resove method bug when calling it on already cancelled promise
cin
parents:
129
diff
changeset
|
35 if (m_locks == 0) { |
| 129 | 36 m_exclusive = false; |
| 37 m_locks = 1; | |
| 38 return true; | |
| 39 } | |
| 40 | |
| 41 if (Monitor.Wait(m_lock, timeout)) { | |
| 42 Debug.Assert(m_locks == 0); | |
| 43 m_locks = 1; | |
| 44 m_exclusive = false; | |
| 45 return true; | |
| 46 } | |
| 47 return false; | |
| 48 } | |
| 49 } | |
| 50 | |
| 51 public void LockShared() { | |
| 52 LockShared(-1); | |
| 53 } | |
| 54 | |
| 55 public void ReleaseShared() { | |
| 56 lock (m_lock) { | |
| 57 if (m_exclusive || m_locks <= 0) | |
| 58 throw new InvalidOperationException(); | |
| 59 m_locks--; | |
| 60 if (m_locks == 0) | |
| 61 Monitor.PulseAll(m_lock); | |
| 62 } | |
| 63 } | |
| 64 | |
| 65 public void ReleaseExclusive() { | |
| 66 lock (m_lock) { | |
| 67 if (!m_exclusive && m_locks != 1) | |
| 68 throw new InvalidOperationException(); | |
| 69 m_locks = 0; | |
| 70 Monitor.PulseAll(m_lock); | |
| 71 } | |
| 72 } | |
| 73 | |
| 74 } | |
| 75 } | |
| 76 |
