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

 

https://blog.csdn.net/oyoung_2012/article/details/78958274

从C++11开始,C++标准库已经支持了线程库了,其实在底层,仍旧使用的是平台相关的线程API
有了std::thread之后,我们就不用在不同的平台使用不同的API了,比如Unix平台使用pthread, windows平台使用WinSDK的CreateThread了,接口使用去掉了平台差异性,使得项目开发具有更好的移植性

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的管理
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

C. 需要引入的库文件

由于Unix平台std::thread底层实现仍旧是pthread, 所以需要增加编译参数 -lpthread

2. std::thread的使用注意事项

A. std::thread不可复制

比如一下代码:

void task1(); //具体实现这里忽略
int main(int argc, char **argv)
{
    std::thread thr1(task1);
    // std::thread thr2 = thr1; //将会编译报错
    thr1.join();
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

B. std::thread在栈内创建后,需要在同一个作用域内调用join() 或者 detach(), 否则退出作用域后,程序会异常退出, 具体原因如下:

这里写图片描述

其中的std::terminate()就是用来终止进程的调用。由于std::thread创建后默认是joinable的, 所以需要调用join()或者detach() 来使线程变成非joinable的状态, 具体使用join()还是detach() 取决于实际需求, 如果需要等待线程完成才能继续,那就使用join()来等待, 如果需要立刻返回继续其他操作, 那就调用detach()来脱离对线程的管理, 两者必须选一个

C. 调用new 创建的std::thread, 禁止直接使用delete, 需要在调用delete之前,调用 join()或者 detach() (如果创建线程后立刻调用了这两个函数中任意一个, 可以不再调用, 但是为了保险起见, 需要加上if(joinable()) 的判断), 原因见上一条

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐