Global variable sharing problem

Hi friends, I am doing project on SILAB c8051F340 based processor, which includes USB communication and PCA for frequency generation. A global counter (unsigned long) is updated in PCA interrupt, read & updated in USB interrupt, and read only in Main loop.

So what care should be taken to avoid conflict within these interrupts.

Thanks in advance, kishore.

Reply to
kishor
Loading thread data ...

Be aware that reading a variable in Main loop may result with erroneous value if this variable is updated in interrupt. For example when the counter is 00 FF and you start reading, you read first the FF value and it may happen interrupt at this moment so the counter will be 01 00 , after returning from interrupt you will read the second byte and the result you get is 01 FF instead of 01 00. The 8-bit processors are more sensible to this problem because they access the variables byte by byte. There are some solutions I suggest:

1) If possible disable PCA interrupt - then you will be sure you read the correct value. I don't know how frequently you read this counter, maybe once for a long time, so disabling interrupt won't be a disaster. 2) Read twice the counter from Main loop and compare the values, if you have the same value you are sure the interrupt didn't occur at this time of reading.
Reply to
YSrebrnik

The PCA is presumably the 8051's timer circuit that can be set to give interrupt at regular interval.

What bugs me is you say you're "updating" this value in both the PCA and the USB interrupts. Can one of these interrupts be invoked while the processor is servicing the other interrupt? If so, you have to take precautions that they don't actually both write to it. If you need (as I suspect but I'm only guessing) the USB interrupt to clear the counter value, you should instead set a clear-the-counter flag. Read this flag in the PCA interrupt routine, and if it's set, clear both the flag and the counter.

The below comments also apply, though instead of "sensible" he no doubt means "sensitive."

Reply to
Ben Bradley

Hi friends, Thanks for reply.

unsigned long gdwGlobal_count (Global variable). This variable stores the total pulse's generated.

It is updated in PCA interrupt. PC reads this "gdwGlobal_count" continuously through USB.

the main problem is that 8051 is little endian & PC is big endian. So when PC requests "gdwGlobal_count" I have to do some calculations and convert it to big endian.

Problem is when PC request frequently (After each 5 ms), my "gdwGlobal_count" changes erratically.

Regards, kishore.

Reply to
kishor

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.