【发布时间】:2016-06-10 19:20:22
【问题描述】:
我有代码可以将任务分派到一个 asio io_service 对象以进行远程处理。据我所知,代码运行正常,但不幸的是,我对内存排序知之甚少,而且我不确定在检查原子标志以确保最佳性能时应该使用哪些内存顺序。
//boost::asio::io_service;
//^^ Declared outside this scope
std::vector<std::atomic_bool> flags(num_of_threads, false);
//std::vector<std::thread> threads(num_of_threads);
//^^ Declared outside this scope, all of them simply call the run() method on io_service
for(int i = 0; i < num_of_threads; i++) {
io_service.post([&, i]{
/*...*/
flags[i].store(true, /*[[[1]]]*/);
});
}
for(std::atomic_bool & atm_bool : flags) while(!atm_bool.load(/*[[[2]]]*/)) std::this_thread::yield();
所以基本上,我想知道的是,我应该用什么来代替[[[1]]] 和[[[2]]]?
如果有帮助,代码在功能上类似于以下内容:
std::vector<std::thread> threads;
for(int i = 0; i < num_of_threads; i++) threads.emplace_back([]{/*...*/});
for(std::thread & thread : threads) thread.join();
除了我的代码使线程在外部线程池中保持活动状态并向它们分派任务。
【问题讨论】:
-
如有疑问,只需保留完整的内存屏障(默认)。
标签: c++ multithreading c++11 boost-asio memory-barriers