stdthreaddetach

Posted thefist11

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stdthreaddetach相关的知识,希望对你有一定的参考价值。

1. 脱离主线程的绑定,主线程挂了,子线程不报错,子线程执行完自动退出。

void pause_thread(int n) 

    std::this_thread::sleep_for (std::chrono::seconds(n));
    std::cout << "pause of " << n << " seconds ended\\n";


int test() 

    std::cout << "Spawning and detaching 3 threads...\\n";
    std::thread (pause_thread,1).detach();
    std::thread (pause_thread,2).detach();
    std::thread (pause_thread,3).detach();
    std::cout << "Done spawning threads.\\n";

    std::cout << "(the main thread will now pause for 5 seconds)\\n";
    // give the detached threads time to finish (but not guaranteed!):
    pause_thread(5);
    return 0;

输出:

Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended 

1.1 当对象析构时线程会继续在后台执行,但是当主程序退出时并不能保证线程能执行完。

        void thread1() 
            for(int i=0;i<20;++i)
                cout << "thread1... " << i << endl;
        

        void thread2() 
            for (int i = 0; i<20; ++i)
                cout << "thread2... " << i << endl;
        

        int test() 
            thread th1(thread1);   //实例化一个线程对象th1,该线程开始执行
            thread th2(thread2);
            th1.detach();
            th2.detach();
            cout << "main..." << endl;
            return 0;
        

输出结果是不确定的

main...thread1... 
detach test
或者
main...thread1... 
detach test
0
0

以上是关于stdthreaddetach的主要内容,如果未能解决你的问题,请参考以下文章