cmultithreadingembeddedvxworks

How to ensure atomicity in VxWorks structure operations?


I have written code involving multiple tasks, in VxWorks. They worked smoothly.

I didn't care about atomic operations, at that point in time. But later, while going through the literature, I found that atomic operations matter when multiple threads access same variable.

I had structures being used by more than one task and it worked fine. But from now on, I would like to be careful. So, are there any methods by which structure operations can be ensured to be atomically safe.


Solution

  • If I understand correctly your question is quite general. You may manage concurrent access to resource (e.g. global variable) in following ways:

    1. using semaphore; each task will "take" semaphore before doing something with that resource and "give" it afterwards, the binary semaphore is the best for this purpose
    2. you may "lock" the task before doing something with that resource and "unlock" it afterwards, this way you make sure that the task will not be rescheduled and no other task can run until you unlock your task
    3. for the case that the resource may be accessed from the interrupt handler (and so the N1 and N2 protection may not work) you may disable all interrupts before and enable them after.

    The last way will always work, but if you will disable interrupts for long time the OS may stop working correctly (e.g. communication may fail on timeout).