當前執行緒的操作

std::this_thread 是一個 namespace,它具有從當前呼叫函式的當前執行緒上做有趣事情的功能。

功能 描述
get_id 返回執行緒的 id
sleep_for 睡眠指定的時間
sleep_until 睡到特定時間
yield 重新安排正在執行的執行緒,為其他執行緒提供優先順序

使用 std::this_thread::get_id 獲取當前執行緒 id:

void foo()
{
    //Print this threads id
    std::cout << std::this_thread::get_id() << '\n';
}

std::thread thread{ foo };
thread.join(); //'threads' id has now been printed, should be something like 12556

foo(); //The id of the main thread is printed, should be something like 2420

使用 std::this_thread::sleep_for 睡 3 秒:

void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

std::thread thread{ foo };
foo.join();

std::cout << "Waited for 3 seconds!\n";

使用 std::this_thread::sleep_until 在將來睡到 3 個小時:

void foo()
{
    std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::hours(3));
}

std::thread thread{ foo };
thread.join();

std::cout << "We are now located 3 hours after the thread has been called\n";

使用 std::this_thread::yield 讓其他執行緒優先:

void foo(int a)
{
    for (int i = 0; i < al ++i)
        std::this_thread::yield(); //Now other threads take priority, because this thread
                                   //isn't doing anything important

    std::cout << "Hello World!\n";
}

std::thread thread{ foo, 10 };
thread.join();