[英]does std::map::end() return different results from different threads?
我有這個線程池,它包含一個對象容器,每當它收到一條新數據時,它就會用相同的新數據更新所有對象。 工作是在線程池的構建上預分配的,這個工作存儲在下面的數據成員中
std::map<std::thread::id, std::vector<unsigned>> m_work_schedule
因此,如果此map
中的線程元素在其vector<unsigned>
中包含元素 1,2 和 3,則意味着它負責在每次新數據點到達時更新索引為 1,2 和 3 的對象。
如果我有十個對象和三個線程,工作計划可能看起來像這樣
140314357151488... 2, 5, 8,
140314365544192... 1, 4, 7,
140314373936896... 0, 3, 6, 9,
在每個工作線程中,它都會進行一些計算,然后將其計算添加到共享聚合變量中。 不過我很困惑,因為一旦所有線程都完成,只有最后一個線程應該對計算進行最后的潤色。 由於某種原因,這個塊偶爾會執行兩次:
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);
}
output 看起來像這樣:
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()
的讀取是否會影響另一個線程的讀取?**我打賭你的問題就在這里
for(unsigned i=0; i< m_num_threads; ++i) {
m_threads.push_back( std::thread(&split_data_thread_pool::worker_thread, this));
most_recent_id = m_threads.back().get_id();
m_work_schedule.insert(std::pair<std::thread::id, std::vector<unsigned> >(most_recent_id, std::vector<unsigned>{}));
m_has_new_dyn_input.insert(std::pair<std::thread::id, bool>(most_recent_id, false));
}
您在填充 m_work_schedule_map 時啟動線程。 據我所知,沒有鎖。 所以你有同時的讀者和作家
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.