Using volatile long as an atomic

后端 未结 6 1886
感动是毒
感动是毒 2021-01-13 14:29

If I have something like this...

volatile long something_global = 0;

long some_public_func()
{
    return something_global++;
}

Would it b

6条回答
  •  盖世英雄少女心
    2021-01-13 15:08

    On modern fast multicore processors, there is a significant overhead with atomic instructions due to caching and write buffers.

    So compilers won't emit atomic instructions just because you added the volatile keyword. You need to resort to inline assembly or compiler-specific extensions (e.g. gcc atomic builtins).

    I recommend using a library. The easy way is to just take a lock when you want to update the variable. Semaphores will probably be faster if they're appropriate to what you're doing. It seems GLib provides a reasonably efficient implementation.

提交回复
热议问题