c++ 11多线程创建 标准线程库

  • 2020-09-23
  • 程序简版
  • 公开
简介thread mytobj(ctc);   //一个新的线程 mytobj.joinable()   //判断能否加入线程 mytobj.join();    //阻塞当前线程 mytobj.detach();    //非阻塞当前线程
thread mytobj(ctc);   //一个新的线程

mytobj.joinable()   //判断能否加入线程

mytobj.join();    //阻塞当前线程

mytobj.detach();    //非阻塞当前线程

文章评论

    c++11多线程创建

        2020-09-23    

    #include <iostream>
    
    #include <thread>
    
    std::thread::id main_thread_id = std::this_thread::get_id();
    
    void hello()  
    {
        std::cout << "Hello Concurrent World\n";
        if (main_thread_id == std::this_thread::get_id())
            std::cout << "This is the main thread.\n";
        else
            std::cout << "This is not the main thread.\n";
    }
    
    void pause_thread(int n) {
        std::this_thread::sleep_for(std::chrono::seconds(n));
        std::cout << "pause of " << n << " seconds ended\n";
    }
    
    int main() {
        std::thread t(hello);
        std::cout << t.hardware_concurrency() << std::endl;//可以并发执行多少个(不准确)
        std::cout << "native_handle " << t.native_handle() << std::endl;//可以并发执行多少个(不准确)
        t.join();
        std::thread a(hello);
        a.detach();
        std::thread threads[5];                         // 默认构造线程
    
        std::cout << "Spawning 5 threads...\n";
        for (int i = 0; i < 5; ++i)
            threads[i] = std::thread(pause_thread, i + 1);   // move-assign threads
        std::cout << "Done spawning threads. Now waiting for them to join:\n";
        for (auto &thread : threads)
            thread.join();
        std::cout << "All threads joined!\n";
    }
评论列表
c++11多线程创建