Atomic operation in multithreaded embedded software

后端 未结 1 538
甜味超标
甜味超标 2021-01-22 21:21

I have been developing an RTOS based embedded software in C and I have encountered a problem regarding shared resource access from several threads. I have two problems. The firs

1条回答
  •  时光说笑
    2021-01-22 22:06

    Both of your questions is the same problem really.

    32 bit MCU means nothing unless you disassemble the code and verify that the operation is indeed a single instruction. This is often not the case with C code.

    Often you have 2 or more instructions like: "load value from stack into register", "do stuff with register", in which case it doesn't matter how many bits your MCU got. You can get an interrupt or context switch in between the two instructions.

    And even if you can verify that the machine code is atomic, that's not necessarily a stable state of affairs. Make changes to the code, add more variables, link again, and suddenly code that was atomic before is atomic no longer, or vice versa.

    C simply has no guarantee of atomicity. Some alternatives if you don't trust the disassembly:

    • C11 _Atomic.
    • Write inline assembler.
    • Use a mutex or similar synchronization mechanism.

    0 讨论(0)
提交回复
热议问题