C++11 多线程 一

本周决定 搞定c++11 多线程


Threads

std::thread 在<thread>头文件,可以配合常规函数,匿名函数(lambdas),仿函数使用,并支持传递任意类型和个数参数传递给绑定的线程函数
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>

void func(int n1, int n2, std::string str)
{
	std::cout << n1 << n2 << str << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
	std::thread t([](){ printf("thread\n" ); });//创建匿名函数线程并<span style="font-family: Arial, Helvetica, sans-serif;">调用函数起始部分</span>
	t.join();//阻塞主线程,等到 t线程执行完毕

	std::thread thread_test(func, rand(), rand(), "abc");//传递任意参数(传值)
	//std::thread thread_test(func, std::ref(rand()),std::(rand()), "abc");//通过std::ref()来传递引用
	thread_test.join();
	//thread_test.detach();//主线程和子线程异步执行  此时要注意主线程生命应大于子线程 
	//t.swap(thread_test);//交换线程handle和id

	system("pause");
	return 0;
}



常规try catch捕捉异常将不起作用  需要存储异常表达式并传递给主线程 下章开始Lock
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值