使用线程时内存分配问题

问题描述

我正在尝试与使用数据分配的结构一起使用。尽管在每个函数中都获得了正确的输出,但是当这些函数通过线程运行时,我仍然遇到了溢出错误。我当前拥有的代码是:

#include <iostream> // cout,endl
#include <thread>   // thread

using namespace std;

// a structure to hold parameters to pass to a thread
struct StatData
{
    // the number of numbers
    int n;
    // the array of numbers
    double *numbers;
};

void average(StatData *data,double *avg) {
    int id;
    int size = data->n;
    double sum = 0.0;

    for(int i = 0; i < size; i++){
        sum += data->numbers[i];
    }
    *avg = sum / size;
}

void minimum(StatData *data,double *min) {
    int id;
    int size = data->n;
    *min = data->numbers[0];

    for(int i = 0; i < size; i++){
        if (*min > data->numbers[i]){
            *min = data->numbers[i];
        }
    }
}

void maximum(StatData *data,double *max) {
    int id;
    int size = data->n;
    *max = data->numbers[0];

    for(int i = 0; i < size; i++){
        if (*max < data->numbers[i]){
            *max = data->numbers[i];
        }
    }
}

int main(int argc,char** argv) {
    // checking if arguments were passed
    if (argc <= 1) {
        cout << "No numbers were passed." << endl;
        cout << "At least one number needs to be entered." << endl;
        return 1;
    }

    // declaring worker threads
    thread avg_t,min_t,max_t;

    // variables for values
    double avg_v;
    double min_v;
    double max_v;

    // initalizing data structure to hold numbers
    StatData data;
    data.n = argc - 1;                  // the amount of numbers passed
    data.numbers = new double[data.n];  // allocating space for nums

    // Filling in the array with numbers using atof
    for (int i = 0; i < data.n; i++) {
        data.numbers[i] = atof(argv[i+1]); // converting string to double
    }

    // creating average thread
    avg_t = thread(average,&data,&avg_v);

    // creating minimum thread
    min_t = thread(minimum,&min_v);

    // creating maximum thread
    max_t = thread(maximum,&max_v);

    // wating for threads to finish
    avg_t.join();
    min_t.join();
    max_t.join();

    printf ("The average value is %d\n",&avg_v);
    printf ("The minimum value is %d\n",&min_v);
    printf ("The maximum value is %d\n",&max_v);

    // freeing up dynamically allocated space
    delete[] data.numbers;
}

当我以47、58和6的值运行./test时,我得到以下打印声明: 平均值是-502425280 最小值是-502425288 最大值为-502425296

我不确定我要去哪里出错导致代码执行此操作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)