您的位置:首页 > 编程语言 > C语言/C++

C++11 多线程 一

2015-11-30 13:34 316 查看
本周决定 搞定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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: