一个简单的程序

  • 一个简单的Hello, Concurrent World程序:
#include<iostream>
#include<thread>
using namespace std;

void hello()
{
	cout << "Hello Concurrent World\n";
}

int main()//初始线程
{
	thread t(hello);//每个线程都必须具有一个初始化函数
	t.join();
	return 0;
}

t.join();的作用:
新的线程启动之后,初始线程继续执行。如果它不等待新线程结束,它就将自顾自地继续运行到main()的结束,从而结束程序——有可能发生在新线程运行之前。

  • 通过函数对象创建线程
#include<iostream>
#include<thread>
using namespace std;

class Counter {
public:
	Counter(int id, int numIterations)
		:mId(id), mNumIterations(numIterations)
	{}
	void operator()() const
	{
		for (int i = 0; i < mNumIterations; i++)
		{
			cout << "Counter " << mId << " has value ";
			cout << i << endl;
		}
	}
private:
	int mId;
	int mNumIterations;
};

int main()
{
	//列表初始化
	thread t1{ Counter{1, 20}};
	Counter c(2, 12);
	thread t2(c);	
	thread t3(Counter(3, 10));	
	t1.join();
	t2.join();
	t3.join();
	return 0;
}

易错点

#include<iostream>
#include<thread>
using namespace std;
class Counter {
public:
	Counter(){}
	void operator()() const
	{}
};

int main()
{
	/*
	如果你传递了一个临时变量,而不是一个命名的变量;
	C++编译器会将其解析为函数声明,而不是类型对象的定义。
	其参数是一个指针,指向返回一个Counter对象的无参函数
	*/
//	thread t2(Counter());	
	thread t2((Counter()));	
	t2.join();
	return 0;
}

  • 通过lambda创建线程
#include<iostream>
#include<thread>
using namespace std;

int main()
{	
	int id = 1;
	int numberIterations = 100;
	thread t4([id, numberIterations] {
		for (int i = 0; i < numberIterations; ++i) {
			cout << "Counter " << id << " has value ";
			cout << i << endl;
		}
	});
	t4.join();
	return 0;
}

lambda表达式:
lambda表达式是C++11的一个新特性,它允许使用一个可以捕获局部变量局部函数

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值