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

7 篇文章 3 订阅

以下代码的编译调试环境为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;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值