vendredi 24 janvier 2020

c++11 std::thread multi param constructor failed to compile [duplicate]

I'm trying to use thread function with multiple parameters, as below:

#include<functional>
#include<iostream>
#include<thread>
using namespace std;
void f(int& j, int& k){
    j+=1;
    k+=1;
}
int main(){
    int j=3;
    int k=4;
    thread t1(f, j, k);
    t1.join();
    cout<<j<<','<<k;
    thread t2(f, ref(j), ref(k));
    t2.join();
    cout<<j<<','<<k;
    return 0;
}

But it gives a lot of compilation errors, both clang++ and g++ gives a lot of weird template errors which I cannot read, like below:

clang++ xxx.cpp -lpthread -std=c++11
In file included from threadParam.cpp:3:
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.4.0/../../../../include/c++/7.4.0/thread:242:40: error: no matching member function for call to          '_M_invoke'
        -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.4.0/../../../../include/c++/7.4.0/thread:127:8: note: in instantiation of template class
    'std::thread::_Invoker<std::tuple<void (*)(int &, int &), int, int> >' requested here
            __make_invoker(std::forward<_Callable>(__f),
            ^
threadParam.cpp:12:12: note: in instantiation of function template specialization 'std::thread::thread<void (&)(int &, int &), int &, int       &>' requested here
    thread t1(f, j, k);

Where did I get wrong and how to fix it?

Aucun commentaire:

Enregistrer un commentaire