并发修改和读取单个全局变量

并发修改和读取单个全局变量

本文介绍了C ++并发修改和读取单个全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中只有一个公共变量

I have a single public variable in a class

bool toSwitch = false;

bool toSwitch = false;

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

Func_Thread2()
{
   toSwitch = true;
}

Func_Thread1将被频繁调用(2秒一次),在一定的间隔内,Func_Thread2将被调用(1分钟一次),并将全局变量更改为true.因此,在下一个Func_Thread1调用中,if条件将变为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.

toSwitch是否需要同步,因为它可以同时由不同的线程读取和修改..?

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

更新2:

在这种环境下会发生什么...?

What happens in this environment...?

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

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 .?

推荐答案

如果一个对象被多个线程访问,并且至少一个线程是写程序,则它是数据竞争.

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. 为了使编译器不对访问共享变量的访问进行重新排序.
  2. 让其他线程以一致的方式(原子)及时地(将存储缓冲区刷新到缓存)查看此变量的更新.

您的硬件可能能够以原子方式存储bool,但是,出于上述其余原因,您可能希望使用std::atomic<bool>.

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>.

这篇关于C ++并发修改和读取单个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:32