2016-03-23 21 views
-4

こんにちは私はC++ &スレッドを勉強しています。私はC++を初めて使いました。次のコードは他の言語の経験に基づいています。しかし私にはそれは大丈夫だと思いますが、実行するとコンパイルされますが、実行すると何もしません。私が間違っていることを教えてください。実行中のいくつかのスレッドを取得しようとしてC++の単純なスレッドの例

#include <iostream> 
#include <thread> 
#include <vector> 
#include <string> 

void printLine(std::string str) { 
    std::cout << str << std::endl; 
} 

void child(int id) {  
    printLine("This is a thread with id: " + std::to_string(id)); 
} 

int main() { 

    printLine("This is the main thread and we are baout to spawn threads...");  
    std::vector<std::thread> threads; 

    for (int i = 0; i < 10; i++) { 

     threads[i] = std::thread(child, i);   
     threads[i].join(); 

    } 

    printLine("Press any key to exit..."); 
    std::getchar(); 

    return 0; 

} 
+0

を境界アクセスのうちので、未定義の動作を: 'スレッド[i]を=のstd ::スレッド(子、I) ; '。ベクトル 'threads'は空です。 – juanchopanza

+0

forループの外側でスレッドを使用していないときに、なぜスレッドをスレッドに「追加」していますか? – Default

+0

ダウン投票している人にとって、これは馬鹿馬鹿しい質問だと思っていますが、ダウンして投票するのではなく、少なくとも私のエラーに関する参考情報を提供できれば幸いです。 – Syd

答えて

0

あなたのコードには、テストケースでだ、ここでの問題ではありません。

std::vector<std::thread> threads; 

for (int i = 0; i < 10; i++) { 

    threads[i] = std::thread(child, i);   
    threads[i].join(); 

} 

threadsは、このようにthreads[0]または> 0にアクセスし、forループに入ると空であります未定義の動作につながります。

あなたが実際にそのvectorに要素を追加する代わりに、push_back(またはemplace_back)を使用してください:

std::vector<std::thread> threads; 

for (int i = 0; i < 10; i++) { 

    threads.push_back(std::thread(child, i));   
    threads[i].join(); 
} 
+0

ループでも参加するのは無意味です。 – juanchopanza

+0

@Juanchopanza真実、コードの実際の意味よりむしろUBを引き起こす部分に焦点を当てようとしました。 –