C++11中Thread类简单使用的例子

代码如下:

#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <cmath> 
#include <vector>
#include <cstdlib>

using namespace std;
void helloworld() {
	cout << "hello world" <<endl;
}

double caculate(int v) {
	if (v <= 0) {
		return v;
	}
	this_thread::sleep_for(std::chrono::milliseconds(10));
	return sqrt((v * v + sqrt((v - 5) * (v + 2.5)) / 2.0) / v);
}

template<typename Iter,typename Fun>
double visitRange(thread::id id, Iter iterBegin, Iter iterEnd, Fun fun) {

	auto curId = this_thread::get_id();
	if (id == this_thread::get_id()) {
		cout << curId << "main thread" << endl;
	}
	else {
		cout << curId << "worker thread" << endl;
	}
	double v = 0;
	for (auto iter = iterBegin; iter != iterEnd; ++iter) {
		v += fun(*iter);
	}
	return v;
}



int main()
{
	auto mainThreadId = this_thread::get_id();
	vector<double> v;
	for (int i = 0; i < 1000; i++) {
		v.push_back(rand());
	}
	cout << v.size() << endl;
	double value = 0.0;
	auto st = clock();
	for (auto& info : v) {
		value += caculate(info);
	}
	auto ed = clock();
	cout << "single thread:" << value << " "<<ed - st << "time" << endl;

	auto iterMid = v.begin() + (v.size() / 2);
	double lastPart = 0.0;
	auto iterEnd = v.end();
	st = clock();
	//auto halfPart = visitRange(mainThreadId, v.begin(), iterMid, caculate);
	thread s([&lastPart, mainThreadId, iterMid, iterEnd]() {
		lastPart = visitRange(mainThreadId, iterMid, iterEnd, caculate);
		});

	auto halfPart = visitRange(mainThreadId, v.begin(), iterMid, caculate);

	s.join();
	ed = clock();

	cout << "multi thread: " << (halfPart + lastPart) << " " << ed - st << "time" << endl;


	return 0;
}

Makefile:

CFLAGS=-std=c++11 -pthread
CC=g++
pThreadTest:pThreadTest.cpp
        $(CC) $(CFLAGS) $^ -o $@
.PHONY:clean
clean:
        $(RM) pThreadTest.o pThreadTest

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值