C++11/std::thread - 線程的基本用法

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

如果有興趣可以訪問我的個站:www.stubbornhuang.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章