Home > Software design >  How to implement multiple threads, running the same function, on separate input data
How to implement multiple threads, running the same function, on separate input data

Time:09-24

I am trying to instantiate two threads, running the same function, on two separate data inputs.

I keep getting errors C2672, C2893, and C2780.

What am I doing wrong? I've included the minimum below to show what I am trying to achieve.

#include <iostream>
#include <vector>
#include <thread>
using namespace std;

vector<double> someFunction(vector<double> input) {

    vector<double> output(9, 0);

    int inputSize = input.size();

    for (int i = 0; i < inputSize; i   ) {
        output[i] = 0;
    }

    return output;
}

int main() {

    // Output vectors
    vector<double> tempOne(9, 0);
    vector<double> tempTwo(9, 0);

    // Input data
    vector<double> input1 = {
            2.0, 1.0, 2.0,
            1.0, 3.0, 2.0,
            1.0, 1.0, 4.0,
    };
    vector<double> input2 = {
            2.0, 1.0, 2.0,
            1.0, 3.0, 2.0,
            1.0, 1.0, 4.0,
    };

    // Two threads running the same function, on two seperate data inputs
    thread t0(someFunction(input1), tempOne, 0);
    thread t1(someFunction(input2), tempTwo, 1);

    t0.join();
    t1.join();

    // Print outputs
    for (double &X : tempOne) {
        cout << tempOne[X] << endl;
    }
    for (double& X : tempTwo) {
        cout << tempTwo[X] << endl;
    }
    
    return 0;
}

C2672 - Suppression State Error C2672 'invoke': no matching overloaded function found

C2893 - Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Ty1 &&,_Types2 &&...) noexcept()'

C2780 - 'unknown-type std::invoke(_Callable &&) noexcept()': expects 1 arguments - 3 provided

CodePudding user response:

The function should be

void someFunction(const vector<double>& input, vector<double>& output, int n) {
  output.resize(input.size());
  ...
}

The threads

thread t0(someFunction, cref(input1), ref(tempOne), 0);
thread t1(someFunction, cref(input2), ref(tempTwo), 1);
  • Related