c++ 多线程

Author Avatar ZTFtrue 发表于 • 2017年09月23日 18:48 • 共 • 252 • 次浏览

c++是支持多线程的(好像是·C11以后)

#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];                         // default-constructed threads
    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";


}
最后编辑于 • 2017年09月23日 18:57 •  

你尚未登录,无法进行回复。