Do I need to protect this variable with a lock?

后端 未结 6 1249
天涯浪人
天涯浪人 2021-02-15 11:58

so I have a boolean type in C++ on a multiprocessor machine. The variable starts out life as true, and then there are a few threads, any one or more of which might write it to b

6条回答
  •  遇见更好的自我
    2021-02-15 12:38

    It's an easy way to break things. With a boolean, you may be ok most of the time, but are provided no guarantees.

    You have two options: use a mutex (lock), or use atomic primitives. Atomic primitives will utilize hardware instructions to do the test and set operations in a thread-safe fashion without requiring an actual mutex and are a lighter-weight solution. The GNU compiler provides access to atomic operations via architecture-specific extensions. There are also portable atomic operation libraries floating around; the Glib C library provides atomic operations that fall back to using a mutex if atomic primitives are not available, although it is a fairly heavy library with many other features as well.

    There is the Boost.Atomic library which abstracts atomic operations for C++; based on its name, it looks like it is aiming to be incorporated into the Boost C++ library collection but hasn't yet made it.

提交回复
热议问题