-1

I was doing a project that uses threads to sum some matrix but at the time of creating the threads and adding the params it always shows up the same error. Any ideas?

void sum(std::vector <double>& matrix, std::vector <double>& other) {
    for (auto i = 0; i < 15; i++) {
        matrix[i] += other[i];
    }
}

here it is the operation that threads should do.

std::vector <double>* mat1 = new std::vector <double>[15];
std::vector <double>* mat2 = new std::vector <double>[15];
std::vector <std::thread*> threads;

for (int j = 0; j < 15; j++) {
    sum(mat1[j], mat2[j]);                                          //this works;
    threads.push_back(new std::thread(sum,mat1[j],mat2[j]));        //this dont why?;
}

Thanks in advance

  • 5
    Your use of `new` seems very wrong. There should be no need for any `new` in this code. Raw `new`s are rarely needed in modern C++ and [should be avoided](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new). `std::vector threads;` can be `std::vector threads;`, the pointer is not needed. Similarly for `mat1` and `mat2`. That aside, either variant has undefined behavior, because you are trying to index into the `std::vector`s in `sum`, but they are empty. Please provide a complete [repro], including the error message. – walnut Feb 15 '20 at 15:48
  • 4
    Re: "it always shows ... the same error" -- what error is that? Include the error message in the question. – Pete Becker Feb 15 '20 at 15:49
  • 2
    Your question can not be answered unless you edit to include the error message and minimal example code. – drescherjm Feb 15 '20 at 16:02

1 Answers1

1

To get it to compile, change:

std::thread(sum,mat1[j],mat2[j])

to:

std::thread(sum, std::ref(mat1[j]), std::ref(mat2[j]))

Example: https://godbolt.org/z/Ek-cnm

But there are multiple problems with your question and code besides just getting it to compile, please listen to what other have said in the comments.

DeducibleSteak
  • 1,286
  • 9
  • 20