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

类的非静态成员函数作为线程函数的注意事项

时间:2017-08-26 18:24:44      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:boost thread

代码

#include <string>

#include <boost/thread/thread.hpp>

#include <boost/bind.hpp>

#include <boost/function/function0.hpp>


class CThreadClass

{

public:

CThreadClass()

{

m_stop = true;

}


void StartThread()

{

boost::function0<void> f = boost::bind(&CThreadClass::ThreadFunc, this);

boost::thread thrd(f);

}



void ThreadFunc()

{

std::cout << m_stop << std::endl;

}


private:


bool m_stop;


};


void ThreadTest()

{

CThreadClass helper;

helper.StartThread();

}



int main()

{

ThreadTest();

::Sleep(1000);

return 0;

}


在上面的例子中,在类的构造函数中,初始化m_stop为true,但是在线程函数中访问的时候,m_stop却是为false,并且根据引用,

只有构造函数对m_stop进行了初始化操作


原因

    ThreadTest函数实例化CThreadClass,创建线程,当ThreadTest调用结束的时候,helper实例就会由于生命周期结束,

而在栈中被销毁,这个时候,m_stop的值就是未知的,有的时候如果寄存器中的值没有被清空,或者置位,程序正常运行

上述代码来自于项目中的不成熟的使用方案,通过该方法来创建一个监听服务,切记!!




优雅


#include <boost/thread/thread.hpp>

#include <boost/bind.hpp>

#include <boost/function/function0.hpp>


class CThreadClass

{

public:

CThreadClass()

{

m_stop = false;

}


void StartThread()

{

m_thread.reset(new boost::thread(boost::bind(&CThreadClass::ThreadFunc, this)));

}


void StopThread()

{

m_stop = true;

m_thread->join();

}



void ThreadFunc()

{

while (!m_stop)

{

std::cout << "thread is running" << std::endl;

::Sleep(100);

}

}


private:


bool m_stop;

boost::shared_ptr<boost::thread> m_thread;


};


CThreadClass* pHelper = NULL;


void StartListen()

{

pHelper = new CThreadClass();

pHelper->StartThread();

}


void StopListen()

{

if (NULL == pHelper) return;

delete pHelper;

pHelper = NULL;

}



int main()

{

StartListen();

::Sleep(1000);

StopListen();

return 0;

}


注意:reset前面是.,而join前面是->,目前没有明白


类的非静态成员函数作为线程函数的注意事项

标签:boost thread

原文地址:http://fengyuzaitu.blog.51cto.com/5218690/1959516

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