当前线程的操作

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();