c++11并发编程二(std::thread之:线程入口函数)

以下代码的编译调试环境为Win7+vs2017

(1)普通函数作为线程入口函数

#include <iostream>
#include <thread>
#include <string>
using namespace std;

void f1(string s)
{
	cout << s << endl;
}


int main() {
	thread thread1(f1, "普通函数"); //函数名、参数
	thread1.join();    

	return 0;
}

(2)类的非静态成员函数作为线程入口函数

#include <iostream>
#include <thread>
#include <string>
using namespace std;

class A
{
public:
	void f2(string s) {
		cout << s << endl;
	}
};
int main() {
	A a;

	std::thread thread(&A::f2, &a, "非静态成员函数作为线程入口"); //传入成员函数地址、 类对象地址、参数
	thread.join();

	return 0;
}

(3)类的静态成员函数作为线程入口函数

#include <iostream>
#include <thread>
#include <string>
using namespace std;

class A
{
public:
	static void f3(string s) {
		cout << s << endl;
	}
};
int main() {
	std::thread thread(A::f3, "静态成员函数作为线程入口"); //传入静态成员函数地址、参数
	thread.join();
	return 0;
}

(4)匿名函数(lambda表达式)作为线程入口函数

#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	//无参的匿名函数
	std::thread t([]()
	{
		std::cout << "lambda thread\n";
	});

	t.join();

	vector<thread> workers;
	//开启五个线程,放入vector,线程入口函数是带一个int参数的匿名函数
	for (int i = 0; i < 5; ++i) {
		workers.push_back(thread([](int x)
		{
			cout << x << endl;
		}, i));
	}
	
	// 通过 for_each 循环每一个线程
	// 第三个参数赋值一个task任务
	// 符号'[]'会告诉编译器我们正在用一个匿名函数
	// lambda函数将它的参数作为线程的引用t
	// 然后一个一个的join
	std::for_each(workers.begin(), workers.end(), [](std::thread &t)
	{
		t.join();
	});
	cout << "main end" << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44843859/article/details/112174179
今日推荐