C++11 thread库 用法举例

join()和detach()

#include "pch.h"
#include <iostream>
#include <thread> 
#include <string>
#include <chrono>
#include <sstream>
#include <ctime>
#include <iomanip>
using namespace std;

void print_time() {
	auto now = chrono::system_clock::now();
	time_t in_time_t = chrono::system_clock::to_time_t(now);
	struct tm *in_time = new tm();
	localtime_s(in_time, &in_time_t);
	std::stringstream ss;
	ss << put_time(in_time, "%Y-%m-%d %X");
	cout << "now is: " << ss.str() << endl;
}

void sleep_thread() {
	this_thread::sleep_for(chrono::seconds(5));  //沉睡5秒
	cout << "[thread-" << this_thread::get_id() << "] is waking up" << endl;
}

void loop_thread() {
	for (int i = 0; i < 10; i++) {
		cout << "[thread-" << this_thread::get_id() << "] print: " << i << endl;
	}
}
int main()
{	
	print_time();
	thread t1(sleep_thread);
	thread t2(loop_thread);
	t1.join();    //等待线程完成
	t2.detach();  //允许线程独立执行
	print_time();
	return 0;  //程序等待线程t1完成后结束,一共运行5秒
}

call_once和once_flag

#include "pch.h"
#include <iostream>
#include <thread> 
#include <string>
#include <mutex>
using namespace std;

void init() {
	cout << "Initialing..." << endl;   //只会被执行一次
}

void worker(once_flag* flag) {
	call_once(*flag, init);
}

int main() {
	once_flag flag;

	thread t1(worker, &flag);
	thread t2(worker, &flag);
	thread t3(worker, &flag);

	t1.join();
	t2.join();
	t3.join();

	return 0;
}

并发

#include "pch.h"
#include <iostream>
#include <thread> 
#include <string>
#include <mutex>
#include <vector>

using namespace std;

static double sum = 0;

static mutex exclusive;

void concurrent_worker(int min, int max) {
	double now_sum = 0;
	for (int i = min; i <= max; i++) {
		now_sum += pow(i,2);
	}
	exclusive.lock();
	sum += now_sum;
	exclusive.unlock();  //只在写的时候加锁,降低锁的粒度,把耗时运算放在外面
}

void concurrent_task(int min,int max) {
	auto start_time = chrono::steady_clock::now();
	unsigned concurrent_count = thread::hardware_concurrency();  //获取硬件真正能并行运行的任务数量
	cout << "hardware_concurrency: " << concurrent_count << endl;
	vector<thread> threads;
	for (int t = 0; t < concurrent_count; t++) {
		int range = max / concurrent_count * (t + 1);
		threads.push_back(thread(concurrent_worker, min, range)); 
		min = range + 1;
	}
	for (int i = 0; i < threads.size(); i++) {
		threads[i].join();
	}

	auto end_time = chrono::steady_clock::now();
	auto ms = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
	cout << "Concurrent task finish, " << ms << " ms consumed, Result: " << sum << endl;
}

int main() {
	concurrent_task(0,4);
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值