这是我的问题。我有几个线程可以修改结构的属性,还有一个线程可以读取结构。如何确定我正在读取的值没有被其他线程更改?就我而言,属性只能由一个线程修改。
例子:
typedef struct
{
int a;
double b;
} data;
data glob;
int main()
{
thread reader([]()
{
while(1)
{
sleep(1s);
cout << glob;
}
});
thread writer1([]()
{
while(1)
glob.a++;
});
thread writer2([]()
{
while(1)
glob.b++;
});
int i;
cin >>i;
}
然后,如何确定当我读取glob时,writer1和writer2并未对其进行修改?
#include <thread>
#include <atomic>
#include <iostream>
#include<chrono>
typedef struct
{
std::atomic_int a;
std::atomic<double> b;
} data;
data glob;
int main()
{
glob.a.store(0);//store data in the atomic variable
glob.b.store(0.0);
std::thread reader([]()
{
while (1)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << glob.a.load() << " " << glob.b.load() << std::endl; //get the value of the variable
}
});
std::thread writer1([]()
{
while (1)
glob.a++;
});
std::thread writer2([]()
{
while (1)
glob.b.store(glob.b.load() +1); // std::atomic<double> has no member operator++ so have to improvise
});
int i;
std::cin >> i;
}
这是<atomic>
用于不可分割的访问和写入操作的简单解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句