So, for the assignment, we need to be able to use C # -Lock or use the self-employed TaS-Lock. What I read about TaS-Locks is that it uses 1 atomic step to read and write the value. We were asked to use the Interlocked class in C # for this.
So far this is what I have, but it seems to lead to inconsistent answers:
public interface Lock { void Lock(); void Unlock(); } public class C_Sharp_Lock : Lock { readonly Object myLock = new object(); public void Lock() { Monitor.Enter(myLock); } public void Unlock() { Monitor.Exit(myLock); } } public class Tas_Lock : Lock { int L = 0; public void Lock() { while (0 == Interlocked.Exchange(ref L, 1)) { }; } public void Unlock() { Interlocked.Exchange(ref L, 0); } }
Does anyone know what I'm doing wrong here?
Edit : as an answer to Kevin's question:
I changed it to the following:
public class Tas_Lock : Lock { int L = 0; public void Lock() { while (0 == Interlocked.CompareExchange(ref L, 1, 0)) { }; } public void Unlock() { Interlocked.Exchange(ref L, 0); } }
However, this still returns inconsistent results.
Change # 2: Changes to C # lock:
public class C_Sharp_Lock : Lock { readonly Object myLock = new object(); bool lockTaken = false; public void Lock() { Monitor.Enter(myLock, ref lockTaken); } public void Unlock() { if (lockTaken) Monitor.Exit(myLock); } }
source share