C++ std::this_thread

2019-09-26  本文已影响0人  土豆吞噬者

命名空间std::this_thread提供了一组关于当前线程的函数。

获取当前线程ID:

int main()
{

    cout << this_thread::get_id() << endl;
    thread t([] {cout << this_thread::get_id() << endl; });
    t.detach();
    system("pause");
}

放弃当前线程的时间片,使CPU重新调度以便其它线程执行:

bool g_ready;
void waitReady()
{
    while (!g_ready) {
        this_thread::yield();
    }
    cout << "ok" << endl;
}

int main()
{
    thread t(waitReady);
    t.detach();
    string inputStr;
    while (cin >> inputStr) {
        if (inputStr == "hello"){
            break;
        }
    }
    g_ready = true;
    system("pause");
}

阻塞当前线程一段时间。

int main()
{
    this_thread::sleep_for(chrono::nanoseconds(1000));//阻塞当前线程1000纳秒
    this_thread::sleep_for(chrono::microseconds(1000));//阻塞当前线程1000微妙
    this_thread::sleep_for(chrono::milliseconds(1000));//阻塞当前线程1000毫秒
    this_thread::sleep_for(chrono::seconds(20)+ chrono::minutes(1));//阻塞当前线程1分钟20秒
    this_thread::sleep_for(chrono::hours(1));//阻塞当前线程1小时
    system("pause");
}

阻塞当前线程直到某个时间点。

int main()
{
    chrono::system_clock::time_point until = chrono::system_clock::now();
    until += chrono::seconds(5);
    this_thread::sleep_until(until);//阻塞到5秒之后
    system("pause");
}
上一篇 下一篇

猜你喜欢

热点阅读