码迷,mamicode.com
首页 > 编程语言 > 详细

C++11多线程01

时间:2016-11-26 22:59:43      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:read   阻塞   span   不能   images   log   ret   nbsp   字符   

#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()

技术分享

 

C++11多线程01

标签:read   阻塞   span   不能   images   log   ret   nbsp   字符   

原文地址:http://www.cnblogs.com/guozhikai/p/6105096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!