【用示例学习与理解C++系列】std::thread的使用与注意点

构造与使用

创建线程实例时通过构造方法可以设置该线程可执行方法,这个方法我们一般称之为线程入口函数,这个入口函数可以是具体的函数或lambda表达式

#include <iostream>
#include <thread>

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 <iostream>
#include <thread>

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;
}

执行结果
在这里插入图片描述

detach不卡线程

不卡线程是不卡调用线程/当前线程,线程的入口函数跟当前线程是并行执行的

#include <iostream>
#include <thread>

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;
}

执行结果
在这里插入图片描述

不调join或detach线程也会启动,但会遇到terminating

不像JAVA线程需要调用start方法线程才会run!!!,但应用会崩溃,出现 terminating的提示,具体原因可阅读 C++在声明一个线程之后不写join()函数或者detach()函数,程序就会报错,这是为什么呢?

#include <iostream>
#include <thread>

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;
}

在这里插入图片描述

相关文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值