2014-06-11 8 views
5

मैं इसे ऐसा करने की कोशिश कर रहा हूं कि मैं एक लूप से धागे को कॉल नहीं कर सकता। लेकिन जब मैं इसे चलाने मैं एक रनटाइम त्रुटि मिलती है:यह सरल धागा कोड क्यों विफल रहता है?

terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument Thread #1

#include <iostream> 
#include <vector> 
#include <memory> 
#include <thread> 
#include <mutex> 

std::mutex m; 
static int thread_count; 

auto foo = [&] { 
    std::lock_guard<std::mutex> lock(m); 
    std::cout << "Thread #" << ++thread_count << std::endl; 
}; 

int main() 
{ 
    std::vector<std::shared_ptr<std::thread>> 
      threads(20, std::make_shared<std::thread>(foo)); 

    for (const auto& th : threads) 
     th->join(); 
} 
+0

@juanchopanza हाँ –

+0

इसे 'पकड़ फेंक' के साथ जीडीबी के तहत चलाएं। –

+2

@ शार्थ सही है। लेकिन 'shared_ptrs' क्यों? – juanchopanza

उत्तर

12

आपका कोड केवल वास्तव में एक बच्चे धागा बनाता है, और इसलिए यह join() कि एक धागा 20 गुना पर कहता है।

इसे प्रमाणित करने के लिए, आपको निम्न पाश जोड़ सकता है सही होने के बाद आप सदिश का निर्माण:

for (int i=1; i<threads.size(); ++i) 
    assert(threads[i - 1].get() == threads[i].get()); 

आप की संभावना के कुछ फार्म के साथ अपने वेक्टर बनाना चाहते हैं:

std::vector<std::shared_ptr<std::thread>> threads(20); 
for (auto & thread : threads) 
    thread = std::make_shared<std::thread>(foo); 
+0

@ डेविडस्वार्टज़ वेक्टर में एक ही साझा_प्टर की कई प्रतियां हैं। या एक ही ऑब्जेक्ट को प्रबंधित करने वाले कई साझा_प्टर्स। – juanchopanza

+2

ओह, आप सही हैं। आपको जवाब में इसे इंगित करना चाहिए। मुख्य अंतर्दृष्टि यह है कि 'make_shared' को केवल एक बार बुलाया जाता है। –

संबंधित मुद्दे