【发布时间】:2016-06-25 12:20:23
【问题描述】:
我在问自己,原子 bool 就绪标志是否可以确保数据在线程之间同步(我已经阅读过这个 Synchronization Mechanism For "data ready" Flag?),但我的问题没有评论答案。
例如看这段代码:
#include<atomic>
#include<thread>
class BIG_DATA {
public:
BIG_DATA(){ std::this_thread::sleep_for(std::chrono::seconds(1)); }//some big data to init ......
};
void init_BIG_DATA(BIG_DATA* & location, std::atomic<bool>& flag ) {
if (flag.load())throw("error : data already loaded");
location = new BIG_DATA(); //heavy operation
flag.store(true);
}
class data {
public:
data() {
ready.store(false);
std::thread t = std::thread(init_BIG_DATA,std::ref(_data),std::ref(ready));
t.detach();
}
BIG_DATA* get_data() {
if (ready.load()) return _data;
else return nullptr;
}
private:
BIG_DATA* _data = nullptr;
std::atomic<bool> ready;
};
如果我有这样的主要代码:
data d;
while (d.get_data() == nullptr) ; // wait for Big data to be constructed in an other thread
BIG_DATA* BD = d.get_data();
// do somethin with big data
我是否确保我对 BIG_DATA* (BD) 所做的事情是正确的,并且该对象在创建者和工作线程之间被同步化? 这段代码线程安全吗?
【问题讨论】:
-
使用
mutex函数,当你的资源在thread中使用时,你可以在此之前锁定mutex变量,完成线程工作后解锁互斥锁。 -
我知道,但我很好奇是否有无锁方法可以做到这一点?如果这行得通?
-
它实际上是用于 sdl 应用程序的图像加载器,我在其中从磁盘或互联网等加载图像
-
注意:不要使用分离,除非你知道自己在做什么:stackoverflow.com/questions/22803600/…
-
这是一种幼稚的同步方法。如果两个函数同时调用 init 函数,它将不起作用,所以不。它不是线程安全的。
标签: c++ multithreading atomic