C++ Thread, shared data

前端 未结 10 1848
悲&欢浪女
悲&欢浪女 2020-12-04 22:35

I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don\'t

10条回答
  •  攒了一身酷
    2020-12-04 23:00

    Yes. No. Maybe.

    First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it).

    Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile

    Volatile considered harmful and Linux Kernel Memory Barriers are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns...

提交回复
热议问题