2016-10-17 4 views
0

まず、私は英語ではありませんので、できる限り良く説明しようとします。 私はこのスレッドを投げます。ここでは、saludoは挨拶を意味し、retardoは遅延を意味し、numeroは数字を意味します。だから、私がやらなければならないことは、スクリーンに5から15回表示される10個のスレッドを作成し、100から300までの遅延で、それらは数字(「大豆」の数字)ですが、そのエラーがあります私は全く解決できません。これは2-3スレッドで動作し、停止します。ありがとうbtw。私はこれを理解していません: 'std :: length_error'のインスタンスをスローした後に呼び出される終了します。

#include <iostream> 
#include <thread> 
#include <string> 
#include <chrono> 
#include <time.h> 

using namespace std; 

void saludo(string m, int retardo, int numero) { 
    string tabs(numero - 1, '\t'); 
    cout << tabs << m << numero << +"\n"; 
    this_thread::sleep_for(chrono::milliseconds(retardo)); 
} 

int main() { 
    int nthread = 10; 
    srand(time(NULL)); 
    thread P[nthread]; 
    int i = 0; 

    while(i<nthread){ 
     int retardo = rand() % 201 + 100; 
     int veces = rand() % 11 + 5; 

     for (int x = 0; x<veces; ++x){ 
      int numero = rand() % 10; 
      P[i] = thread(&saludo, "Soy ", retardo, numero); 
      P[i].join(); 
     } 
    } 

    cout << "Fin\n"; 
    return 0; 
} 

答えて

3

このエラーは、std :: stringコンストラクタに負の数値を渡した可能性があるためです。 rand() % 10は0を与えるかもしれません。numeroが0の場合はstring tabs(numero - 1, '\t');が問題になります。

関連する問題