C++11 新特性之std::thread

1. std::thread的使用方法
A. 所需头文件
#include <thread>
1
B. 具体使用的几种方式
//1. 直接使用函数
void thread1_process(int code)
{
    std::cout << "code: " << code << std::endl;
}

int code  = 0; // get code from somewhere
std::thread thread1(thread1_process, code);
thread1.join(); // 等待线程结束
//tread1.detach(); // 将线程脱离thread1的管理

/**********************************************************************/
//2. 使用类成员函数
struct Task
{
 void doSomething(int task_type) {
    std::cout << "task_type: " << task_type<< std::endl; 
    // TODO
 }
};
Task task1;
std::thread thread2(&Task::doSomething, &task1, 1);
thread2.join(); // 等待线程结束
//tread2.detach(); // 将线程脱离thread2的管理

/***********************************************************************/
//3. 使用std::bind
Task task2;
std::thread thread3(std::bind(&Task::doSomething, &task2, 2));
thread3.join(); // 等待线程结束
//tread3.detach(); // 将线程脱离thread3的管理

/***********************************************************************/
//4. 使用lambda表达式
std::thread thread4([](){
    std::cout << "lambda thread called." <<std::enld; 
});
thread4.join(); // 等待线程结束
//tread4.detach(); // 将线程脱离thread4的管理
--------------------- 
作者:逗神大人 
来源:CSDN 
原文:https://blog.csdn.net/oyoung_2012/article/details/78958274 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值