0

I have a function add which takes three integers and a reference to an integer. I would like to pass this function to a thread. This is what I've done so far:

void add(int a, int& b, int c, int& acc) {
    acc += a + b + c;
}

int main() {
    int acc = 0;
    
    std::thread t1(add, 1, 2, 3, acc);
    std::thread t2(add, 4, 5, 6, acc);

    t1.join();
    t2.join();

    std::cout << acc;

    return 0;
}

But this does not compile. This is just a simple example of the problem, but actually the function I want to pass to the thread takes in a pointer to an array. One way is to use a vector, but is there another solution?

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
  • You might want to re-word the question's title -- right now it's not clear if it indicates "How to pass (a function that takes a reference) to a thread" or "How to pass a function (that takes a reference to a thread)" – Jeremy Friesner Oct 07 '21 at 20:10
  • I too thought of it when typing the question, but the ambiguity is resolved after reading the body of the question. – Wais Kamal Oct 07 '21 at 20:13
  • You may pass a lambda to thread that internally call your add function (c++11 and over) – IkarusDeveloper Oct 07 '21 at 21:07

0 Answers0