创建线程的几种方式

class A {
	int x;
public:
	void f(int x, char c) {  };
	int operator()(int N) { return 0; }
};
void foo(int x){}
int main() {
	A a;
	
	thread t1(a, 6); // 传递a的拷贝给子线程
	
	thread t2(ref(a), 6); //传递a的引用给子线程
	thread t3(move(a), 6); //a在主线程中将不再有效
	
	thread t4(A(), 6); //传递临时创建的a对象给子线程
	
	thread t5(foo, 6); //通过函数创建子线程
	thread t6([](int x) {return x * x; }, 6); //lambda表达式
	
	thread t7(&A::f, a, 8, 'w'); //传递a的拷贝的成员函数给子线程
	
	thread t8(&A::f, &a, 8, 'w'); //传递a的地址的成员函数给子线程
	
	future<int> fu = async(launch::async, &A::f, &a, 6); //调用async函数的时候就开始创建新线程
	fu.get(); //  阻塞 等待线程fu结束

	future<int> fu1 = async(launch::deferred, &A::f, &a, 6); // launch::deferred表示延迟调用
	fu1.get(); //get()函数时,才执行入口函数

	future<int> fu2 = async(launch::async | launch::deferred, &A::f, &a, 6); // 可能创建新线程,也可能延迟调用 都加和不加一样
	future<int> fu3 = async(&A::f, &a, 6);
	fu2.get();
	fu3.get();
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值