我有这个
thread pool
它包含一个对象容器,每当接收到一条新数据时,它都会用相同的新数据更新所有对象。该工作是在线程池的构造上预先分配的,并且该工作存储在以下数据成员中
std::map<std::thread::id, std::vector<unsigned>> m_work_schedule
所以如果一个线程的元素
map
元素1、2和3在其
vector<unsigned>
,这意味着它负责在每次新数据点到达时用索引1、2和3更新对象。
如果我有十个对象和三个线程,工作时间表可能会像这样
140314357151488... 2, 5, 8,
140314365544192... 1, 4, 7,
140314373936896... 0, 3, 6, 9,
每
worker thread
,它进行一些计算,然后将其计算添加到共享聚合变量中。但我很困惑,因为
一旦所有的线程都完成了,只有最后一个线程应该对计算进行最后的润色。
由于某种原因,这个街区是
偶尔地
执行两次:
if( std::prev(m_work_schedule.end())->first == std::this_thread::get_id() ){
std::cout << "about to finalize from thread " << std::this_thread::get_id() << ", which supposedly is equal to " << (--m_work_schedule.end())->first << "\n";
m_working_agg = m_final_f(m_working_agg);
m_out.set_value(m_working_agg);
}
输出如下所示:
139680503645952... 2, 5, 8,
139680512038656... 1, 4, 7,
139680520431360... 0, 3, 6, 9,
about to finalize from thread 139680520431360, which supposedly is equal to 139680520431360
................
about to finalize from thread 139680503645952, which supposedly is equal to 139680503645952
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: Promise already satisfied
但是,这段代码怎么能运行两次呢?
我只是在读报纸
m_work_schedule
但这种偶然性表明这是某种种族状况。不过,我很难想出任何可能的解释。
-
是吗
std::map::end()
在不同的线程中返回不同的内容?
-
一条线的读数与
std::map::end()
影响其他线程的**
-
如果最后一个线程在所有线程完成工作之前完成,它能再次随机输入这段代码吗?
-
线程ID可以更改吗?