Atomic Safety Methodologies

1 post / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
//Method 1
volatile U32 g_data1=0,g_data2=0,g_data3=0;
void Interrupt()
{
	g_data1++;
	g_data2++;
	g_data3++;
}
void GetCurrentValues()
{
	U32 a, b, c;
	NVIC_DisableIRQ(MYISR_IRQn);
	a = g_data1;
	b = g_data2;
	c = g_data3;
	NVIC_EnableIRQ(MYISR_IRQn);
	if(a != b || b != c)
	{
		//ATOMIC SAFETY FAILED!
	}
	else
	{
		//DATA IS OK
	}	
}


//Method 2
//read atomically using a flag system
//If flag is 0, then Interrupt is allowed to modify the data and write 1 to flag when done.
//If flag is 1, then main loop is allowed to read data, and write 0 to flag when done.
volatile U32 g_data1=0,g_data2=0,g_data3=0;
volatile U32 g_FLG=0; //Measure Flag... 1=MeasurementIsReady 0=Measuring
void Interrupt()
{
	if(g_FLG){return;}//not allowed to modify data yet, main loop still needs to read previous values first
	g_data1++;
	g_data2++;
	g_data3++;
        g_FLG=1; //data is ready for mainloop to read
}
void GetCurrentValues()
{
	U32 a, b, c;
	if(g_FLG==0){return;}//still measuring, do not try to read data yet...
	a = g_data1;
	b = g_data2;
	c = g_data3;
	g_FLG  = 0;//we extracted the measured data, reset flag so interrupt can take next measurement
	if(a != b || b != c)
	{
		//ATOMIC SAFETY FAILED!
	}
	else
	{
		//DATA IS OK
	}
}

/*
Method1 will always update the data.
Method2 will come back later to modify or read the data.
*/

Both methods work fine when I tested them... But does anyone foresee any problems with Method2?

I know that method2 is a different type of idea, the Interrupt and MainLoop take turns modifying the data, and if one is not finished, you just "comes back later" when trying to read or modify the data. But in some application cases this may be just fine, and it carries the benefit of not having to disable the Interrupt.