第三课:C++线程管理

本文介绍了C++中用于多线程操作的四个关键函数:get_id用于获取线程ID,sleep_for和sleep_until分别用于设定线程延时,yield则使线程放弃执行权给其他线程。通过示例代码展示了这些函数的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、下面主要了解四个函数的作用

1、get_id()             获取线程ID  
2、sleep_for()       延时时间函数
3、yield()               让线程放弃执行,让操作系统调用另一个线程
4、sleep_until()     获取当前系统传转换本地时间,阻塞线程

#include<thread>
#include<ctime>
#include<chrono>
#include<iostream>
#include<time>
#include<iomanip>

using namespace std;
using namespace this_thread;

/*
1、get_id()          获取线程ID  
2、sleep_for()       延时时间函数
3、yield()           让线程放弃执行,让操作系统调用另一个线程
4、sleep_until()     获取当前系统传转换本地时间,阻塞线程
*/


//1、get_id() 获取线程ID  

void threadFunc()
{
    cout<<"线程ID:"<<this_thread::get_id()<<endl; 
}

//2、sleep_for() 延时时间函数

void threadSleep_for()
{
    cout<<"线程ID:"<<this_thread::get_id()<<"线程启动"<<endl; 
    this_thread::sleep_for(5s);
    this_thread::sleep_for(chrono::seconds(100));
    cout<<"线程ID:"<<this_thread::get_id()<<"线程结束"<<endl; 
}

//3、yield() 让线程放弃执行,让操作系统调用另一个线程执行

void threadYield(chrono::microseconds duration)
{
    cout<<"线程ID:"<<this_thread::get_id()<<"线程启动"<<endl; 
    auto startTime = chrono::high_resolution_clock::now();    //当前系统时间
    auto endTime = starTime + duration;                       //结束时间
    do
    {
        this_thread::yield();
/*
   需要实现其他功能,写在里面即可
*/
        cout<<1<<endl;    

    }while(chrono::high_resolution_clock::now() < endTime);
    
     cout<<"线程ID:"<<this_thread::get_id()<<"线程结束"<<endl; 
}

//4、获取当前系统传转换本地时间,阻塞线程 

void threadSleep_until()
{
    time_t cP = chrono::system_clock::to_time_t(chrono::system_clock::now()); 
    tm *ptm = new tm;
    localtime_s(ptm,&t);
     
    if(!ptm != nullptr)
    {
        this_thread::sleep_until(chrono::system_clock::from_time_t(mktime(ptm)));
    }
    cout<<put_time(ptm,"%X")<<endl;
}


int main()
{
     cout<<"主线线程ID:"<<this_thread::get_id()<<endl; 
    
    thread t1(threadFunc);
    t1.join();
    
    thread t2(threadSleep_for);
    t2.join();
           
    thread test(threadYield,chrono::microseconds(100));
    test.join();         
          
    threadSleep_until();
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值