CRITICAL_SECTION for set and get single bool value

前端 未结 4 1712
甜味超标
甜味超标 2021-01-19 11:20

now writing complicated class and felt that I use to much CRITICAL_SECTION.

As far as I know there are atomic operations for some types, th

相关标签:
4条回答
  • 2021-01-19 11:56

    You cannot guarantee for all implementations/platforms/compilers that bool, or any other type, or most operations, are atomic. So, no, I don't believe your statements are correct. You can retool your logic or use other means of establishing atomicity, but you probably can't get away with just removing CRITICAL_SECTION usage if you rely on it.

    0 讨论(0)
  • 2021-01-19 11:59

    Note: This answer applies to Windows and says nothing of other platforms.

    There are no InterlockedRead or InterlockedWrite functions; simple reads and writes with the correct integer size (and alignment) are atomic on Windows ("Simple reads and writes to properly-aligned 32-bit variables are atomic operations.").

    (and there are no cache problems since a properly-aligned variable is always on a single cache line).

    However, reading and modifying such variables (or any other variable) are not atomic:

    • Read a bool? Fine. Test-And-Set a bool? Better use InterlockedCompareExchange.
    • Overwrite an integer? great! Add to it? Critical section.
    0 讨论(0)
  • 2021-01-19 12:00

    Here this can be found:

    Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.

    Result should be correct but in programming it is better not to trust should. There still remains small possibility of failure because of CPU cache.

    0 讨论(0)
  • 2021-01-19 12:07
    1. You don't need locks round atomic data, but internally they might lock. Note for example, C++11's std::atomic has a is_lock_free function.
    2. bool may not be atomic. See here and here
    0 讨论(0)
提交回复
热议问题