Three ways to create threads
introduction
一开始,C++是不支持多线程的,直到C++ 11开始,才真正引入了多线程这个概念和标准库。
如果想在cpp文件,比如project.cpp里面使用多线程,需要引入header file
#include <thread>
在编译的时候,需要使用-lpthread:
g++ project.cpp -lpthread
thread creation
每个C++ application里面都有一个默认线程main。如果我们想要创建额外的线程,首先需要创建std::thread class的objects。每一个std::thread object是和一个thread绑定到一起的。将一个callback function与std::thread object绑定到一起,线程开始运行的时候,这个callback function就会被执行:
std::thread thread_object(CALLBACK)
CALLBACK可以是以下三种之一:
- function pointer
- function objects what is function object
- lambda function what is lambda function
creating threads with function pointer
#include <iostream>
#include <thread>
#include <string>
void worker(int tid, const std::string& name){
for(int i = 0; i < 3; ++i){
std::cout << "woker " << tid << name << " is working" << std::endl;
}
std::cout << "worker exits" << std::endl;
}
int main(){
std::thread thread_obj_1(worker, 0, std::string(" Alice"));// worker是function pointer,
std::thread thread_obj_2(worker, 1, std::string(" Bob")); // 1和std::strin