gpt4 book ai didi

C++ 线程 : terminate called without an active exception

转载 作者:行者123 更新时间:2023-11-27 22:51:19 24 4
gpt4 key购买 nike

我正在尝试创建一个不重复的整数数组。要得到长度超过 1000 的数组,需要花费大量的时间来制作。所以,我认为使用线程是一个不错的决定。但是我写错了。到目前为止,以下是我的代码:

utils.h

#ifndef UTILS_H
#define UTILS_H

typedef long long int64; typedef unsigned long long uint64;

class utils
{
public:
utils();
virtual ~utils();
static int getRandomNumberInRange(int min, int max);
static int* getRandomArray(int size, bool isRepeatAllowed);

protected:

private:
};

#endif // UTILS_H

utils.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <vector>
#include <algorithm> // for std::find
#include <sys/time.h>
#include <cctype>
#include <string>
#include <thread>
#include <vector>

#include "utils.h"

utils::utils()
{

}

utils::~utils()
{

}
int utils::getRandomNumberInRange(int min, int max)
{
if (min > max) {
int aux = min;
min = max;
max = aux;
}
else if (min == max) {
return min;
}
return (rand() % (max - min)) + min;
}

void getUniqueInteger(int* arr, int last, int* newVal)
{
int val = *newVal;
while(std::find(arr, arr+last, val) != arr+last)
{
val = utils::getRandomNumberInRange(10, 10000);
}
arr[last] = val;
}

int* utils::getRandomArray(int size, bool isRepeatAllowed)
{
int* arr = new int[size], newVal = 0;
std::vector<std::thread *> threadArr;

for (int i = 0; i < size; i++)
{
newVal = utils::getRandomNumberInRange(10, 1000);
if(!isRepeatAllowed)
{
std::thread newThread(getUniqueInteger, arr, i, &newVal);
threadArr.push_back( &newThread);
}
else
{
arr[i] = newVal;
}
}

int spawnedThreadCount = threadArr.size();

if (spawnedThreadCount > 0)
{
for (int j = 0; j < spawnedThreadCount; j++)
{
threadArr[j]->join();
//delete threadArr[j];
}
}

return arr;
}

并调用它:

main.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

#include "utils.h"

using namespace std;

int main(int argc, char *argv[])
{
if (argc != 2 && utils::isInteger(argv[1]))
{
cout << "You have to provide an integer input to this program!!!" << endl;
return 0;
}

int size = stoi( argv[1] );

srand(time(NULL));

int* arr = utils::getRandomArray(size, false);

return 0;
}

编译方式:g++ -Wall -g -std=c++11 -pthread -o a.out ./utils.cpp ./main.cpp

但是,每当我通过 ./a.out 10 运行程序时,它都会通过给出输出终止:

terminate called without an active exception
Aborted (core dumped)

请帮忙。提前致谢。

最佳答案

您创建线程的代码会创建一个立即销毁的堆栈变量。你需要改变这个:

    if(!isRepeatAllowed)
{
std::thread newThread(getUniqueInteger, arr, i, &newVal);
threadArr.push_back( &newThread);
}

为此:

    if(!isRepeatAllowed)
{
std::thread* newThread = new std::thread(getUniqueInteger, arr, i, &newVal);
threadArr.push_back( newThread);
}

然后稍后取消注释您的删除行。

关于C++ 线程 : terminate called without an active exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37024545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com