Search code examples
c++multithreadingc++20invoke

How can I fix C++ error C2672 in my code with threads?


When I'm trying to compile program with threads, C2672 error ('invoke': no matching overloaded function found) is occuring.

My code:

#include <iostream>
#include <thread>
// the procedure for array 2 filling
void bar(int sum2)
{
    for (int i = 100000; i < 200000; i++) {
        sum2 = sum2 + (i + 1);
        std::cout << sum2;
    }
}
int main()
{
    // the second counter initialization
    int sum2 = 0;
    // the constructor for the thread
    std::cout << "staring thread2...\n";
    std::thread thread(bar);
    // the thread detaching
    thread.detach();
    // the first counter initialization
    int sum1 = 0;
    // filling of the first array
    for (int i = 0; i < 100000; i++) {
        sum1 = sum1 + (i + 1);
        // elements output
        std::cout << sum1;
    }
}

Tell me please, how to fix this bug?


Solution

  • You need to pass a value to the thread you're creating,

    std::thread thread(bar, N);

    where N is the integer value, as you've defined in your void bar(int) function.

    #include <iostream>
    #include <thread>
    
    // the procedure for array 2 filling
    void bar(int sum2)
    {
        for (int i = 100000; i < 200000; i++) {
            sum2 = sum2 + (i + 1);
            std::cout << sum2;
        }
    }
    
    int main()
    {
        // the second counter initialization
        int sum2 = 0;
        // the constructor for the thread
        std::cout << "staring thread2...\n";
        std::thread thread(bar, 100);
        // the thread detaching
        thread.detach();
        // the first counter initialization
        int sum1 = 0;
        // filling of the first array
        for (int i = 0; i < 100000; i++) {
            sum1 = sum1 + (i + 1);
            // elements output
            std::cout << sum1;
        }
        return 0;
    }