【C++多线程系列】【二】线程启动函数的参数传递需类型匹配

给线程的执行函数传递参数时,一定要参数匹配,否则会有编译问题。不同的编译器处理可能不一样。

1.vs2013编译通过。

#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编译失败

#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");
}

提示参数类型不匹配,即函数f参数所需的类型与传入的参数类型不匹配。

修改如下,编译通过。

#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");
}

结果如下:

总结:给线程启动函数传递参数时,类型一定要匹配。否则不是编译问题,就是运行结果与预期不符。

猜你喜欢

转载自my.oschina.net/u/3800567/blog/1798154