资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Boost线程中类内线程函数的示例分析

本篇文章给大家分享的是有关Boost线程中类内线程函数的示例分析,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

公司主营业务:做网站、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出同安免费做网站回馈大家。

代码

#include

#include

#include

#include

class CThreadClass

{

public:

CThreadClass()

{

m_stop = true;

}

void StartThread()

{

boost::function0 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

#include

#include

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 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线程中类内线程函数的示例分析,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


本文名称:Boost线程中类内线程函数的示例分析
转载注明:http://cdkjz.cn/article/gojgee.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220