1 获取CPU核心数量

使用std::thread::hardware_concurrency()获取当前CPU核心数量。
代码示例:

#include <iostream>
#include <thread>


int main()
{
    std::cout << std::thread::hardware_concurrency() << std::endl;
    getchar();
    return 0;
}

2 获取当前线程ID

get_id()可用于获取当前线程的id。
代码示例:

#include <iostream>
#include <thread>


int main()
{
    std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };
    std::cout << thread.get_id() << std::endl;

    thread.join();

    getchar();
    return 0;
}

3 线程休眠

3.1 sleep_for让当前线程休眠一段时间

#include <iostream>
#include <thread>


int main()
{
    std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };
    std::this_thread::sleep_for(std::chrono::seconds(1));

    std::cout << thread.get_id() << std::endl;

    thread.join();

    getchar();
    return 0;
}

3.2 sleep_until让当前线程休眠一直到指定时间

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

#pragma warning(disable:4996)//加上可去掉unsafe 请使用localtime_s的编译报错

int main()
{
    std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };

    std::time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    struct std::tm * ptm = std::localtime(&tt);

    std::cout << "当前时间为: " << std::put_time(ptm, "%X") << std::endl;    

    // 设定线程被唤醒时间为1分钟后
    ptm->tm_min += 1;

    std::this_thread::sleep_until(std::chrono::system_clock::from_time_t(mktime(ptm)));

    std::cout << thread.get_id() << std::endl;

    std::cout << "线程重新被唤起时间为:" << std::put_time(ptm, "%X") << std::endl;;

    thread.join();

    getchar();
    return 0;
}

4 yield

yield放弃当前线程执行,回到准备状态,重新分配cpu资源。所以调用该方法后,可能执行其他线程,也可能还是执行该线程。

#include <iostream>             
#include <thread>         
#include <chrono>          


int main()
{
    bool ready = false;
    std::thread thread{ [&] {
        while (!ready)
        {
            std::cout << "线程函数被挂起" << std::endl;
            std::this_thread::yield();
            ready = true;
        }    
        std::cout << "线程函数被启动" << std::endl;
    } };


    thread.join();

    getchar();
    return 0;
}

当前分类随机文章推荐

全站随机文章推荐

关于本站站长 StubbornHuang
C++11/std::thread – 线程的基本用法-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。