C++多线程编程: 线程

线程

C++11开始, 标准库支持线程操作, 不再需要写多平台的线程代码了: 使用Windows下的Create系列函数以及Linux下的pthread系列函数.

thread

thread是一个线程对象, 它的构造函数可以直接放入要运行的函数以及函数的参数.

demo

首先在子线程中打印参数字符串消息, 然后打印自己的Thread ID, 最后主线程使用join等待子线程结束.

#include <thread>
#include <exception>
#include <iostream>

using namespace std;

void func(const string &msg)
{
	thread::id thrd_id = this_thread::get_id();
	cout << "Other Thread ID: " << thrd_id << endl;
	cout << "Message        : " << msg << endl;
}

int main()
{
	try {
		thread::id thrd_id = this_thread::get_id();
		cout << "Main Thread ID: " << thrd_id << endl;
		
		thread thrd(func, "hello");
		/* do something at main thread */
		thrd.join();
	} catch (exception &e) {
		cout << "Exception: " << e.what() << endl;
	}
	return 0;
}

注: c++也支持线程detach, 但是detach使用场景很少且很容易出现问题, 最好不要使用detach.

future & async

future对象是thread对象的高层接口, 与asyncget配合使用, 可理解为处理并发运算的未来结果.

async对象的构造函数能让一个可被调用的对象成为一个独立的线程并在后台运行.

get成员函数则用于等待线程结束并获取其结果

关于get, 需要知道以下五点:

  1. 如果async已经运行完, 则get能立即获得结果.
  2. 如果async运行的线程还未运行完, 则getjoin的功能相似, 不过get能获取返回值.
  3. 如果async没有运行成功, 则get函数会同步执行调用可被调用的对象.
  4. 一个future对象只能调用一次get, 之后对象处于无效状态, 只能通过vaild成员函数检测.
  5. 如果想调用多次get, 则需要使用shared_future对象.

future

demo

计算1~N的和

#include <future>
#include <exception>
#include <iostream>

using namespace std;

int calc(const int limit)
{
	int sum = 0;
	
	for (int num = 1; num <= limit; ++num) {
		sum += num;
	}
	
	return sum;
}

int main()
{
	int limit;
	cin >> limit;
	
	try {
		future<int> thrd(async(calc, limit));
		cout << "Sum of 1 to " << limit << ": " << flush;
		int result = thrd.get();
		cout << result << endl;
	} catch (exception &e) {
		cout << "Exception: " << e.what() << endl;
	}
	return 0;
}

shared_future

demo


promise

demo


others

demo

转载于:https://my.oschina.net/u/4078154/blog/3011654

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值