C++ Concurrent modification and read of a single global variable

和自甴很熟 提交于 2019-12-14 02:12:39

问题


I have a single public variable in a class

bool toSwitch = false;

Func_Thread1()
{
   if(toSwitch)
   {
      .....
      ....
      toSwitch = false;
   }
}

and

Func_Thread2()
{
   toSwitch = true;
}

The Func_Thread1 will get called frequently(2 seconds once) and during certain interval Func_Thread2 will get called(1 minute once) and change the global variable to true. So at the next Func_Thread1 call the if condition will become true.

Does the toSwitch needs synchronization as it can read and modified by different threads concurrently ..?

Update 2:

What happens in this environment...?

 Func_Thread1()
    {
       if(toSwitch)
       {
          .....
          ....
       }
       else
       {
         ...
       }
    }

and

Func_Thread2()
{
   if(toSwitch)
   {
    toSwitch = false;
   }
   else
   {
     toSwitch = true;
   }
}

Does sync needs here , where one thread modifies and other thread reads the value of that global variable .?


回答1:


If an object is accessed by more than one thread and at least one thread is a writer that is a data race.

You need synchronization for the following reasons:

  1. For the compiler to not reorder your reads and writes around access to the shared variable.
  2. For other threads to see updates to this variable in consistent (atomic) and timely (flush the store buffer to the cache) fashion.

Your hardware is likely to be able to store a bool in atomic fashion, however, for the remaining reasons above you may like to use std::atomic<bool>.




回答2:


You need synchronization. Unsynchronized access to a shared memory location (toSwitch) from more than one thread where at least one access is a write (toSwitch = true;) constitutes a data race, which makes the behaviour of your program undefined.



来源:https://stackoverflow.com/questions/32819166/c-concurrent-modification-and-read-of-a-single-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!