Do I need to use locking with integers in c++ threads

前端 未结 7 1467
慢半拍i
慢半拍i 2021-01-04 21:10

If I am accessing a single integer type (e.g. long, int, bool, etc...) in multiple threads, do I need to use a synchronisation mechanism such as a mutex to lock them. My un

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 21:32

    If you're on a machine with more than one core, you need to do things properly even though writes of an integer are atomic. The issues are two-fold:

    1. You need to stop the compiler from optimizing out the actual write! (Somewhat important this. ;-))
    2. You need memory barriers (not things modeled in C) to make sure the other cores take notice of the fact that you've changed things. Otherwise you'll be tangled up in caches between all the processors and other dirty details like that.

    If it was just the first thing, you'd be OK with marking the variable volatile, but the second is really the killer and you will only really see the difference on a multicore machine. Which happens to be an architecture that is becoming far more common than it used to be… Oops! Time to stop being sloppy; use the correct mutex (or synchronization or whatever) code for your platform and all the details of how to make memory work like you believe it to will go away.

提交回复
热议问题