美文网首页
C++ std::this_thread

C++ std::this_thread

作者: 土豆吞噬者 | 来源:发表于2019-09-26 21:33 被阅读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");
}

相关文章

  • C++11新特性

    std::this_thread::yield() 看代码如下: (1) std::this_thread::yi...

  • C++ std::this_thread

    命名空间std::this_thread提供了一组关于当前线程的函数。 获取当前线程ID: 放弃当前线程的时间片,...

  • C++常用类型转换备忘

    std::string ->const char * c++内置数值类型->std::stringcpp11 支持...

  • C++字符串处理小结

    C++中的字符串类型 常用的C++的字符串类型主要是std::string。它是模板std::basic_stri...

  • 2018-10-23 step

    C++ 11 几个特性的整理 std::future - std::promise 解决的问题 返回值的异步获取:...

  • { 1 }CPP_线程管理的基础

    一,启动线程 1. 使用C++线程库启动线程,即为构造std::thread对象: std::thread构造方法...

  • C++类重载函数的function和bind使用

    C++类重载函数的function和bind使用 在没有C++11的std::function和std::bind...

  • 翻译:“to_string” isn't a member of

    Stack overflow地址:c++ - "to_string" isn't a member of "std...

  • C++

    1.using namespace std; 告诉编译器使用 std 命名空间。 2.C++ 关键字 C++ 中的...

  • 2.1线程管理基础

    启动线程 使用C++线程库启动线程可以归结为构造std::thread对象: std::thread可以用可调用(...

网友评论

      本文标题:C++ std::this_thread

      本文链接:https://www.haomeiwen.com/subject/gcmxyctx.html