For assignment (this is for concurrency if you're interested) - I need to implement my own lock
(more specifically: a TaS, a TTas and Array-Lock, as described in the "Multiprocessor Programming Program")
There are several test I / O circuits on the Internet that I have tried (it is too bad that they have been trying for a long time to try).
Your program is designed to count 9-digit numbers that pass a specific test
(It was called elfproef in Dutch, I do not know English equivalence, sorry).
Sometimes I got a slightly different number, which suggests that my lock does not work 100% to the right.
I implemented locks as follows:
interface Lock
{
void Lock();
void Unlock();
}
class TaSLock : Lock
{
AtomicBool state = new AtomicBool(false);
void Lock.Lock()
{ while (state.getAndSet(true)); }
void Lock.Unlock()
{ state.getAndSet(false); }
}
AtomicBool integer, Interlocked Boolean. , ( ) .
class AtomicBool
{
int value;
static int True = 1, False = -1;
public AtomicBool(bool value)
{
if (value) this.value = True;
else this.value = False;
}
public void set(bool newValue)
{
if (newValue) Interlocked.Exchange(ref value, True);
else Interlocked.Exchange(ref value, False);
}
public bool getAndSet(bool newValue)
{
int oldValue;
if (newValue) oldValue = Interlocked.Exchange(ref value, True);
else oldValue = Interlocked.Exchange(ref value, False);
return (oldValue == True);
}
public bool get()
{
return (Interlocked.Add(ref value, 0) == 1);
}
}
, :
theLock.Lock();
counter++;
theLock.Unlock();
.
- , ?