C++11多线程01

#include <iostream>
#include <thread>

void thread_fun()
{
    std::cout<<"我是线程函数"<<std::endl;
}


int main()
{
    std::thread t(thread_fun);

    t.join(); //运行线程函数,主线程阻塞在这里,直到thread_fun()执行完毕

    return 0;
}

 

 

#include <iostream>
#include <thread>

void thread_fun()
{
    std::cout<<"我是线程函数"<<std::endl;
}


int main()
{
    std::thread t(thread_fun);

    t.detach(); //运行线程函数,不阻塞主线程

    return 0;
}

控制台没有显示任何字符,原因:使用detach开启子线程没有阻塞主线程,主线程已经执行完毕。

 

 

#include <iostream>
#include <thread>

void thread_fun()
{
    std::cout<<"我是线程函数"<<std::endl;
}


int main()
{
    std::thread t(thread_fun);

    t.detach(); //运行线程函数,不阻塞主线程

    t.join(); //detach后,不能再使用join

    return 0;
}

结论:detach后,不能再使用join

 

 

#include <iostream>
#include <thread>

void thread_fun()
{
    std::cout<<"我是线程函数"<<std::endl;
}


int main()
{
    std::thread t(thread_fun);

    t.detach(); //运行线程函数,不阻塞主线程

    if(t.joinable())
    {
        t.join(); //detach后,不能再使用join
    }
    else
    {
        std::cout<<"detach后,不能再使用join"<<std::endl;
    }


    return 0;
}

结论:可以使用joinable()判断是否可以join()

 

posted @ 2016-11-26 20:11  郭志凯  阅读(695)  评论(0编辑  收藏  举报