c++ - 我不明白这个 : terminate called after throwing an instance of 'std::length_error'

标签 c++ multithreading

首先,我不是英语,所以我会尽力解释。 我抛出这个线程,其中 saludo 表示问候,retardo 表示延迟,numero 表示数字,我还创建了 veces 来多次说这会发生。所以我要做的是创建 10 个线程,它们将在屏幕上显示 5 到 15 次,并且延迟从 100 到 300,它们是一个数字(“Soy”数字),但我有这个错误我根本无法解决。它适用于 2-3 个线程,然后停止。顺便说一句,谢谢。

#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;
}

最佳答案

此错误是因为您可能已将负数传递给 std::string 构造函数。 rand() % 10 可能会给出 0。而你正在执行 string tabs(numero - 1, '\t'); 如果 numero 为 0。

关于c++ - 我不明白这个 : terminate called after throwing an instance of 'std::length_error' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40082769/

相关文章:

c# - 为什么我不能获得独占锁?

c++ - 如何在 Visual Studio 中使用 g++ 编译器

java - 如何从多个线程测试一个类的线程安全性?

Android 渲染和物理在不同的线程上?

multithreading - 线程更新 GUI

java - 取前如何查看BlockingQueue头元素?

c++ - 在 C++ 中加载 CLR,Start() 问题

c++ - 从 C 调用共享 .so 中的函数

c++ - 为什么我们需要在 move 构造函数中将右值引用设置为空?

c++ - boost进程间容器适契约(Contract)进程线程共享存储吗?