栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

构造与使用

创建线程实例时通过构造方法可以设置该线程可执行方法,这个方法我们一般称之为线程入口函数,这个入口函数可以是具体的函数或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;
}

执行结果

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};
    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 
#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()函数,程序就会报错,这是为什么呢?
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034096.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号