Interrupts... Thread Safe?

Morning folks. Last night I had my robot responding to an interrupt whenever the encoder pulsed which would simply (leftEncoder++;) increment a counter. I would have the program send send the counter (leftEncoder.toString():wink: out the XBEE. All seemed fine… rotate the wheel and see the count on the XBEE comms. However after a few minutes, the Fez seemed to lock up.

The only thing I can think of at this time is perhaps this is caused by reading a value that is being modified by another thread. Am I way off base here or not?

For reference, I don’t believe its the XBEE as I have sent gps data out it for hours with no problem.

We need sample code as something’s amiss!! Some of us here may see a small hicup in your code and put you straight.

Cheers Ian

Increment is both a read and a write which is *not thread safe. At least in .Net. In netmf, I assume same, but not much writen on the memory model.

The “increment” is not atomic. A write to an int is atomic - which means different threads will not see a “torn” read, but the read-write operation in total is not atomic. To be fully atomic, use a lock or Interlocked.Increment. Your interupt is on another thread (set a Debugger.Break() in your callback to see all the threads).

Thanks! It seems Gus has better things for me to do right now so my focus has changed some. :slight_smile:

Doesn’t really answer the original question but the Interlocked.Increment and Interlocked.Decrement static methods in System.Theading should be thread safe and (supposedly) fast.