When passing parameters to the execution function of the thread, the parameters must match, otherwise there will be compilation problems. Different compilers may handle it differently.
1.vs2013 compiled and passed.
#include<iostream>
#include<thread>
using namespace std;
typedef struct _A
{
int a;
}A;
void f(A &a)
{
cout << a.a << endl;
a.a++;
cout << a.a << endl;
}
int main(int argc, int * argv[])
{
A a = { 1 };
cout << a.a << endl;
// 这里vs2013编译通过,vs2017编译失败
thread t(f,a);
t.join();
cout << a.a << endl;
system("pause");
}
2.vs2017 compilation failed
#include<iostream>
#include<thread>
using namespace std;
typedef struct _A
{
int a;
}A;
void f(A &a)
{
cout << a.a << endl;
a.a++;
cout << a.a << endl;
}
int main(int argc, int * argv[])
{
A a = { 1 };
cout << a.a << endl;
// 这里vs2013编译通过,vs2017编译失败
thread t(f,a);
t.join();
cout << a.a << endl;
system("pause");
}
Prompt parameter type mismatch, that is, the required type of the function f parameter does not match the incoming parameter type.
The modification is as follows, and the compilation is passed.
#include<iostream>
#include<thread>
using namespace std;
typedef struct _A
{
int a;
}A;
void f(A &a)
{
cout << a.a << endl;
a.a++;
cout << a.a << endl;
}
int main(int argc, int * argv[])
{
A a = { 1 };
cout << a.a << endl;
thread t(f,std::ref(a));
t.join();
cout << a.a << endl;
system("pause");
}
The result is as follows:
Summary: When passing parameters to the thread startup function, the types must match. Otherwise, it is not a compilation problem, or the running result is not as expected.