所以我需要一個線程池用於我的應用程序,這導致我創建一個std::map<int, std::thread>
對象。 我遇到一些很意外的行爲,這可以簡化爲這樣:使用std :: thread使用std :: map的意外行爲
std::map<int, std::thread> threads;
threads.insert(std::pair<int, std::thread>(1, std::thread([]() {
std::cout << "I'm the first thread and I'm gonna work\n";
})));
threads[1].join();
std::cout << "Thread 1 joinable? " << threads[1].joinable() << "\n";
threads.insert(std::pair<int, std::thread>(1, std::thread([]() {
std::cout << "I'm not gonna work at all\n";
})));
threads[1].join();
輸出是
I'm the first thread and I'm gonna work
Thread 1 joinable? 0
後立刻std::terminate()
被調用,程序接收SIGABRT信號。
現場調試提示terminate
被調用,因爲joinable()
是真的,但我只是檢查,並認爲它不是!
而且,要克服它只是後join()
ING添加以下行的方式:
threads.erase(1);
這讓我有點困惑,因爲它看起來像的std::thread
一個新的實例是前剛剛創造了我insert
打電話...有人可以提示我這種意外的行爲嗎?
在stdout上跟蹤時,不要忘記刷新。 – molbdnilo
@molbdnilo - 換行符應該這樣做。 –
@OliverCharlesworth''\ n''不會刷新'std :: cout'。 –