Do I need to protect this variable with a lock?

后端 未结 6 1258
天涯浪人
天涯浪人 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条回答
  •  Happy的楠姐
    2021-02-15 12:53

    On most commodity hardware single word read and writes are not atomic operations; remember you have virtual memory machines here and either of those operations might cause a page fault.

    In more general terms you'll probably find it easier and quicker to use mutexes as a matter of routine than scratch your head wondering if you are going to get away without one this time. Adding one where it isn't necessary doesn't cause a bug; leaving one out where it is might.

提交回复
热议问题