简体   繁体   English

多线程中的变量访问,不同步

[英]Variable access in multiple threads with out synchronization

I have following code 我有以下代码

int i; //gobal var

Thread1:
{
...
  i=some value;
}

Thread2:
{
  if (i==2) dosomething();
  else dosomethingelse();
  i = 4;
}

I want to write it to be thread safe without using synchronization objects and in C++ standard way. 我想将其编写为线程安全的,而不使用同步对象并以C ++标准方式进行编写。

my questions is how to have a variable to read/write access by different threads with out using synchronization? 我的问题是如何在不使用同步的情况下使变量具有不同线程的读/写访问权限? my requirement is have a bool variable which can have true or false. 我的要求是拥有一个布尔变量,该变量可以为true或false。

Is volatile variable is atomic. 是volatile变量是原子的。

Please note that i am not supposed to use any libraires like TBB which has atomic variable. 请注意,我不应该使用具有原子变量的TBB之类的书库。

Reason for asking this question we don't want to take and release semphore every time we access the variable in thread, as this variable changed not very often. 提出这个问题的原因是我们不想每次访问线程中的变量时都要花很多时间去释放亮点,因为该变量的更改不是很频繁。

Well your code does not have any meaning right now. 那么,您的代码现在没有任何意义。 Becaues you are basically saying` 因为您基本上是在说`

Thread2:
{
  if (i==2) dosomething();
  //let's do something if i is 2 at the moment I am reading it.
  else dosomethingelse();
  i = 4;
}`

It is ok. 没关系。 But if you are doing something with i then you are in trouble. 但是,如果您与i做某事,那么您就会遇到麻烦。 If not, and if you are asking whether accessing i is atomic or not, it depends on cpu architecture. 如果不是,并且询问访问i是否是原子的,则取决于cpu体系结构。 For example for x86 and x64 it is atomic. 例如对于x86和x64,它是原子的。 Read this . 阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM