Whenever there is a chance that executing code that is using a data item can be interrupted by code that may also use the same data item before the first user has completed its operation on the data item, we have a data-sharing issue. An atomic operation is an operation that is non-interruptible and once started, must complete.
main()
{
INT32 LastCounter = 0;
while(not exiting)
{
if (Counter != LastCounter)
{
LastCounter = Counter;
TextOut(“Count %d\n”, LastCounter);
}
}
}
InterruptA()
{
Counter++;
}
Struct {
UINT32 arrayCount;
UCHAR data[MAX_ARRAY]
} DATALOG, *PDATALOG;
DATALOG samples;
ThreadA() // creator of data
{
newSample = ReadNewData()
if (samples->arrayCount < MAX_ARRAY)
{
samples->Data[samples->arrayCount++] = newSample;
}
else
{
// error case or handle wrap around
}
}
ThreadB() // consumer of data
{
UINT32 lastSample = 0;
if (samples->ArrayCount > lastSample)
{
newSample = samples->data[lastSample++];
ProcessSample(newSample);
//handle wrap around
}
}
// creator of data
ThreadA()
{
newSample = ReadNewData();
if (samples->arrayCount < MAX_ARRAY)
{
OsSchedLock();
samples->data[samples->arrayCount++] = newSample;
OsSchedUnlock();
}
else
{
HandleError();
}
}
// consumer of data
ThreadB()
{
UINT32 sastSample = 0;
OsSchedLock();
if (samples->arrayCount > lastSample)
{
newSample = samples->data[lastSample++];
OsSchedUnlock();
ProcessSample(newSample);
}
else
{
OsSchedUnlock();
}
}
INT32 Counter = 0;
main()
{
INT32 lastCounter = 0;
while(notExiting)
{
OS_ENTER_CRITICAL_SECTION();
if (counter != lastCounter)
{
lastCounter = counter;
OS_EXIT_CRITICAL_SECTION();
TextOut(“Count %d\n”, lastCounter);
}
else
{
OS_EXIT_CRITICAL_SECTION();
}
}
}
InterruptA()
{
Counter++;
}