1测试例子
#include <iostream>
#include <string>
#include <boost/thread/thread.hpp>
void ThreadFunc()
{
std::cout << "Welcome to thread function" << std::endl;
}
int main(int argc, char* argv[])
{
boost::thread instance(&ThreadFunc);
instance.join();
return 0;
}
2 携带参数例子
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
void threadFunc(const char* pszContext)
{
std::cout << pszContext << std::endl;
}
int main(int argc, char* argv[])
{
char* pszContext = "fengyuzaitu@126.com";
boost::thread thread1(boost::bind(&threadFunc, pszContext));
thread1.join();
return 0;
}
3 类的非静态函数作为线程函数
生产环境中经常需要访问类的私有成员,如果类的静态函数作为线程函数,通过参数的方式传递极其不方便
#include <iostream>
#include <string>
#include <boost/thread/thread.hpp>
#include <boost/function/function0.hpp>
class CThreadClass
{
public:
CThreadClass()
{
memset(m_szContext, 0x00, 1024);
}
void ThreadFunc()
{
std::cout << m_szContext << std::endl;
}
void StartThread()
{
strcpy_s(m_szContext, "Welcome to thread func\n");
boost::function0<void> f = boost::bind(&CThreadClass::ThreadFunc, this);
boost::thread thrd(f);
thrd.join();
}
private:
char m_szContext[1024];
};
int main(int argc, char* argv[])
{
CThreadClass instance;
instance.StartThread();
return 0;
}
4 创建线程过多,导致boost库异常抛出,耗尽资源
查看boost::system::system_error = {m_error_code={m_val=11 m_cat=0x02d848f4 {CMMS-test.exe!boost::system::`anonymous-namespace'::generic_error_category generic_category_const} {...} } ...}
boost::throw_exception<boost::thread_resource_error>(const boost::thread_resource_error & e) 行 69 C++
boost::thread::start_thread() 行 180 C++
目前通过代码测试生成1274个线程,实际上这是需要根据线程函数的实质内容决定的,在编码中必须指定上限,否则会引起程序异常崩溃
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。