C++ 多线程之线程管理函数

简介: 这篇文章介绍了C++中多线程编程的几个关键函数,包括获取线程ID的`get_id()`,延时函数`sleep_for()`,线程让步函数`yield()`,以及阻塞线程直到指定时间的`sleep_until()`。

写在前面:

好像突然发现没有啥写的, 那就不写了。哈哈哈~~~

1. 获取线程 id 函数 get_id()的使用

该函数在命名空间std::this_thread下。作用是获取当前线程的id。

#include <iostream>
#include <thread>
using namespace std;

//No.1 get_id() 获取线程id
void threadFunc() {
    cout << "get_id() 子线程id: " << this_thread::get_id() << endl;
    using namespace this_thread;
    cout << "get_id() 子线程id: " << get_id() << endl;
}
void test01() {
    cout << "主线程id: " << this_thread::get_id() << endl;
    thread t1(threadFunc);
    t1.join();
}
int main() {

    test01();
    return 0;
}

2. 延时函数sleep_for()的使用

该函数在命名空间std::this_thread下。作用是延时。

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

//No.2 sleep_for() 延时函数
void threadSleepFor() {
    using namespace this_thread;
    cout << "子线程id: " << get_id()  << " 线程启动!" << endl;

    this_thread::sleep_for(2s); //文本重载方式 延时两秒

    sleep_for(chrono::seconds(2)); //延时两秒

    using namespace chrono;
    sleep_for(seconds(2));

    cout << "子线程id: " << get_id() << " 线程结束!" << endl;
}
void test02() {
    thread t2(threadSleepFor);
    t2.join();
}

int main() {

    test02();
    return 0;
}

线程启动后, 在线程处理函数中,会延时一段时间。延时结束后,继续执行未执行完的线程处理函数。

3. 线程让步函数yield()的使用

该函数在命名空间std::this_thread下。作用是让当前线程让步,让操作系统执行另一个线程。

#include <iostream>
#include <thread>
#include <chrono>
#include <windows.h>
using namespace std;

//No.3 yield()    线程让步(让线程放弃执行, 让操作系统调用另一个线程执行)
void threadYield(chrono::milliseconds duration) {   //间隔时间ms
    using namespace this_thread;
    cout << "yield: 子线程id: " << get_id() << " 线程开始!" << endl;

    //使用高精度时钟获取当前时间
    auto startTime = chrono::high_resolution_clock::now();
    auto endTime = startTime + duration;
    do {
        //线程让步
        yield();
    } while (chrono::high_resolution_clock::now() < endTime);

    cout << "yield: 子线程id: " << get_id() << " 线程结束!" << endl;
}
//chrono::microseconds 微秒
void test03() {
    thread at[5];
    //线程1让步 5 秒
    at[0] = thread(threadYield, chrono::milliseconds(5000));
    //其余四个线程让步 0 秒(每隔一秒创建一个线程)
    for (int i = 1; i < 5; i++) {
        this_thread::sleep_for(1s);
        at[i] = thread(threadYield, chrono::milliseconds(0));
    }
    for (auto& th : at) {
        th.join();
    }
}
int main() {

    system("color F0");
    test03();

    return 0;
}

由下面的运行结果可知,第一个(线程id为12304)的 线程会等待5秒(线程让步5秒),此时操作系统会执行下面的四个线程,待5秒之后,让步的线程(线程id为12304)的线程处理函数继续向下执行。

4. 阻塞线程函数sleep_until()的使用

该函数在命名空间std::this_thread下。作用是阻塞当前线程,直到sleep_time溢出。

#include <iostream>
#include <thread>
#include <chrono>
#include <iomanip>
#include <windows.h>
using namespace std;

void threadFunc() {
    cout << "get_id() 子线程id: " << this_thread::get_id() << endl;
    using namespace this_thread;
    cout << "get_id() 子线程id: " << get_id() << endl;
}

//No.4 sleep_until() 阻塞当前执行线程 直到sleep_time溢出
void threadSleepUntil() {
    cout << "sleep_until: 子线程id: " << this_thread::get_id() << " 线程开始!" << endl;

    time_t tt = chrono::system_clock::to_time_t(chrono::system_clock::now());
    tm* ptm = new tm;
    localtime_s(ptm, &tt);
    cout << put_time(ptm, "%X") << endl;
    //设置sleep_time为5秒
    for (int i = 0; i < 5; i++)
    {
        ++ptm->tm_sec;
    }
    if (ptm != nullptr) {
        this_thread::sleep_until(chrono::system_clock::from_time_t(mktime(ptm)));
    }
    cout << put_time(ptm, "%X") << endl;

    cout << "sleep_until: 子线程id: " << this_thread::get_id() << " 线程结束!" << endl;
}
void test04() {
    thread t1(threadSleepUntil);
    this_thread::sleep_for(1s);
    thread t2(threadFunc);
    t1.join();
    t2.join();
}
int main() {
    system("color F0");
    test04();

    return 0;
}

由下面的运行结果可知,线程t1会进入阻塞状态(sleep_time)阻塞5秒钟,然后t2线程会执行,5秒后t1线程退出阻塞状态,继续执行t1线程的线程处理函数。

相关文章
|
27天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
3天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
370 16
|
19天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
6天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
21天前
|
人工智能 IDE 程序员
期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟
在云栖大会上,阿里云云原生应用平台负责人丁宇宣布,「通义灵码」完成全面升级,并正式发布 AI 程序员。
|
23天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2592 22
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
5天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
181 2
|
3天前
|
编译器 C#
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
105 65
|
7天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
332 2
|
23天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1580 17
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码