C++11线程学习之等待线程结束

       一旦我们开启了新线程后,就需要决定是要等待这个线程结束还是将其设置为分离状态(自行运行,与父线程没什么关系了)。如果不等待线程运行结束的话,有一个问题我们需要注意:必须确保该线程结束前访问到的数据都是有效的,否则会引发异常或输出一些预料之外的结果。

  实例一:

//-----------main.cpp
#include <iostream>
#include <thread>

void do_something(int i)
{
    std::cout << "i = " << i << std::endl;
}

struct func
{
    int& i;
    func(int& i_):i(i_){}
    void operator()()
    {
        for(unsigned j=0;j<1000000;++j)
        {
            do_something(i);
        }
    }

};

void oops()
{
    int some_local_state=8;
    func my_func(some_local_state);
    std::thread my_thread(my_func);
    my_thread.detach(); // 将线程设置为分离状态
}

int main()
{
    oops();
    std::cout << "Hello World!" << std::endl;
}

其中,func类对象引用了oops函数的some_local_state这个局部变量,当oops函数退出的时候,局部变量会自动销毁,此时线程仍然继续运行,则访问到的some_local_state是一个销毁的变量,会输出我们意想不到的结果。

        通常,调用join函数等待线程结束。在启动新线程之后且在调用join函数之前,如果有异常的出现,则很可能会跳过join()的调用。为避免应用程序可能因抛出的异常而终止的情况,下边提供一些解决这样问题的方案。

实例二:在实例一的基础上,使用简单的try...catch...异常捕获机制。

//-----------main.cpp
#include <iostream>
#include <thread>

void do_something(int i)
{
    std::cout << "i = " << i << std::endl;
}

void do_something_in_current_thread()
{
}

struct func
{
    int& i;
    func(int& i_):i(i_){}
    void operator()()
    {
        for(unsigned j=0;j<10;++j)
        {
            do_something(i);
        }
    }

};

void f()
{
    int some_local_state=0;
    func my_func(some_local_state);
    std::thread t(my_func);
    try
    {
        do_something_in_current_thread();
    }
    catch(...)
    {
        t.join();   // execute this when has exception.
        throw;
    }
    t.join(); //  execute this when has no exception.
}
int main()
{
    f();
    std::cout << "Hello World!\n" << std::endl;
}

实例三:使用C++RAII技术处理

RAII技术:我们在C++中经常使用new申请了内存空间,但是却也经常忘记delete回收申请的空间,容易造成内存溢出,于是RAII技术就诞生了,来解决这样的问题。RAII(Resource Acquisition Is Initialization)机制是Bjarne Stroustrup首先提出的,是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术

//-----------main.cpp
#include <iostream>
#include <thread>

void do_something(int i)
{
    std::cout << "i = " << i << std::endl;
}

void do_something_in_current_thread()
{
}

struct func
{
    int& i;
    func(int& i_):i(i_){}
    void operator()()
    {
        for(unsigned j=0;j<10;++j)
        {
            do_something(i);
        }
    }

};

class thread_guard
{
    std::thread& t;
public:
    explicit thread_guard(std::thread& t_):
    t(t_)
    {}
    ~thread_guard()
    {
        // tests to see if the std::thread object is joinable()
        // because join() can be called only once for a given thread of execution
        if(t.joinable())
        {
            t.join();
        }
    }

    // 禁止编译器自动生成拷贝构造和拷贝赋值函数。
    thread_guard(thread_guard const&)=delete;
    thread_guard& operator=(thread_guard const&)=delete;
};

void f()
{
    int some_local_state=0;
    func my_func(some_local_state);
    std::thread t(my_func);
    thread_guard g(t);
}
int main()
{
    f();
    std::cout << "Hello World!\n" << std::endl;
}

输出结果如下:

i = 0
i = 0
i = 0
i = 0
i = 0
i = 0
i = 0
i = 0
i = 0
i = 0
Hello World!

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值