C++多线程

本文讨论的是C++ 11标准下使用thread,mutex等实现多线程的方法,而不是linux中使用pthread实现的方法。


C++11中提供了头文件<thread>、<mutex>、<atomic>、<future>用于支持多线程。

首先是创建一个线程,参考下面的代码。

thread t([] {cout << "new thread!" << endl; });
t.join();
cout << "main thread!";
第一句声明了一个thread类的实例并调用其构造函数,参数为该线程需要执行的函数。此处用lambda表达式书写,有关lambda表达式的介绍,参考本人另一篇文章:C++中使用lambda( http://blog.youkuaiyun.com/xiahn1a/article/details/41665339)。

第二局使用join阻塞原线程,插入新线程直到其执行完毕。

所以输出结果为:

new thread!

main thread!

如果是线程中执行的函数要带参数,再举一个例子。

thread t([](int a, int b) { cout << a + b << endl; }, 1, 2);
t.join();
可以看出,所需执行的函数中有两个参数,那么在thread类的构造函数中就需要给出参数的值。

在本例中会输出3。


获取进程id的方法是调用get_id()函数,方法如下:

this_thread::get_id()
在不同进程中取到的是自己进程的id。


使进程睡眠的方法是调用sleep_for()函数,参数chrono名空间下定义的一个时间长度,方法如下:

this_thread::sleep_for(chrono::seconds(1));
其中seconds可以换成minutes,hours等时间单位。


最后给一个例子说明mutex的使用,利用互斥信号灯在进程间共享数据。

假定有两个进程,分别都能对同一个变量进行加一,输出执行情况。

mutex m;
int count = 0;
auto increase = [&]  //定义增加函数
{
	m.lock();  //用于互斥访问的锁
	count++;
	cout << "id: " << this_thread::get_id() << endl;
	m.unlock();
	this_thread::sleep_for(chrono::milliseconds(100));
};
thread t1([increase]
{
	for (int i = 0; i < 5; i++)
		increase();
});
thread t2([increase]
{
	for (int i = 0; i < 5; i++)
		increase();
});
t1.join();
t2.join();
输出结果如下:


可以看出两个进程是交替输出结果的。

代码中用到了一个类,叫做mutex,用于进程互斥访问。其中lock与unlock函数是对于共享变量的PV操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值