创建线程实例时通过构造方法可以设置该线程可执行方法,这个方法我们一般称之为线程入口函数,这个入口函数可以是具体的函数或lambda表达式
#include#include using namespace std; void sayHi() { for (int i = 0; i < 5; ++i) { cout << "Hi..." << endl; this_thread::sleep_for(chrono::seconds(1)); } } void printName(string name) { while (1) { cout << "Hello, " << name << endl; this_thread::sleep_for(chrono::seconds(2)); } } int main() { //无参函数 thread t1 {sayHi}; t1.detach(); //有参数的函数的情况,第一个参数是函数名,后面可变参数,参数各数必须跟前面函数定义的参数一一对应 thread t2 {printName, "Lily"}; t2.detach(); // lambda thread t3 {[] { for (int i = 0; i < 5; ++i) { cout << "lambda..." << endl; this_thread::sleep_for(chrono::seconds(1)); } }}; t3.detach(); this_thread::sleep_for(chrono::seconds(6)); cout << "main end!!!" << endl; return 0; }
运行结果
Join卡线程thread的join方法会卡线调用线程/当前线程,直到thread的线程入口函数执行结束
#include#include using namespace std; void sayHi() { for (int i = 0; i < 5; ++i) { cout << "Hi..." << endl; this_thread::sleep_for(chrono::seconds(1)); } } int main() { thread t1 {sayHi}; t1.join(); cout << "main end!!!" << endl; return 0; }
执行结果
不卡线程是指导卡调用线程/当前线程,线程的入口函数跟当前线程是并行执行的
#include#include using namespace std; void sayHi() { for (int i = 0; i < 5; ++i) { cout << "Hi..." << endl; this_thread::sleep_for(chrono::seconds(1)); } } int main() { thread t1 {sayHi}; t1.detach(); for (int i = 0; i < 5; ++i) { cout << "Hi...in main" << endl; this_thread::sleep_for(chrono::seconds(1)); } cout << "main end!!!" << endl; return 0; }
执行结果
不像JAVA线程需要调用start方法线程才会run!!!,但应用会崩溃,出现 terminating的提示,具体原因可阅读 C++在声明一个线程之后不写join()函数或者detach()函数,程序就会报错,这是为什么呢?
#include相关文章#include using namespace std; void sayHi() { for (int i = 0; i < 5; ++i) { cout << "Hi..." << endl; this_thread::sleep_for(chrono::seconds(1)); } } int main() { { thread t1{sayHi}; this_thread::sleep_for(chrono::seconds(3)); // t1.detach(); //人为加多加一层局部作用域,下面的cout没有调用之前,thread的构造方法就可以提前执行到 } cout << "main end!!!" << endl; return 0; }
- 深入剖析C++11线程库std::thread,迈入多线程编程的大门
- 十分钟掌握C++中std::thread的基础用法
- c++线程对象既不调用detach又不调用join会发生什么?
- C++在声明一个线程之后不写join()函数或者detach()函数,程序就会报错,这是为什么呢?



