C ++ Boost多线程奇怪的行为
Posted
技术标签:
【中文标题】C ++ Boost多线程奇怪的行为【英文标题】:C++ Boost multithreading strange behavior 【发布时间】:2018-03-10 18:25:23 【问题描述】:我正在关注 Boost 多线程教程here .代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
using std::cout;
using std::cin;
using std::endl;
class CallableClass
private:
// Number of iterations
int m_iterations;
public:
// Default constructor
CallableClass()
m_iterations = 10;
// Constructor with number of iterations
CallableClass(int iterations)
m_iterations = iterations;
// Copy constructor
CallableClass(const CallableClass& source)
m_iterations = source.m_iterations;
// Destructor
~CallableClass()
cout << "Callable class exiting." << endl;
// Assignment operator
CallableClass& operator = (const CallableClass& source)
m_iterations = source.m_iterations;
return *this;
// Static function called by thread
static void StaticFunction()
for (int i = 0; i < 10; i++) // Hard-coded upper limit
cout << i << " - Do something in parallel (Static function)." << endl;
boost::this_thread::yield(); // 'yield' discussed in section 18.6
// Operator() called by the thread
void operator () ()
for (int i = 0; i < m_iterations; i++)
cout << i << " - Do something in parallel (operator() )." << endl;
boost::this_thread::yield(); // 'yield' discussed in section 18.6
;
int main()
boost::thread t(&CallableClass::StaticFunction);
for (int i = 0; i < 10; i++)
cout << i << " - Do something in main method." << endl;
return 0;
但是,如果我将 main() 更改为此:
int main()
// Using a callable object as thread function
int numberIterations = 20;
CallableClass c(numberIterations);
boost::thread t(c);
for (int i = 0; i < 10; i++)
cout << i << " - Do something in main method." << endl;
return 0;
在执行运算符之前调用类析构函数。我不太理解这种行为。调用析构函数时,类不应该停止执行吗?另外,为什么运算符有两组括号?我如何知道第二个线程(不是 main())何时停止并安全退出?谢谢。
【问题讨论】:
【参考方案1】:No boost::thread
在被破坏时不会停止执行。 std::thread
不允许您这样做,如果您在未加入线程的情况下破坏线程,则会调用 std::terminate
。
您需要在 main() 方法的末尾添加 t.join()
。
void operator () ()
是没有参数的()操作符,第一个()是操作符的名字,第二个()是参数列表。例如,带有参数的可调用类如下所示:
struct s
void operator ()( int p ) ;
【讨论】:
这是否意味着它是一个失控线程,占用内存和 CPU 功率? 可能不会,当它尝试使用的 c 成员不复存在时,它会很快崩溃。当 main 返回时,该进程通常会终止 在t.join()
之前使用t.joinable()
不会有什么坏处
不会有什么坏处,但由于线程是在该方法的早期创建的,据我所知,在这种情况下它总是可以连接的。
那么知道析构函数没有表示它的终止,我怎么知道它什么时候终止呢?以上是关于C ++ Boost多线程奇怪的行为的主要内容,如果未能解决你的问题,请参考以下文章
使用多线程处理多个http请求HttpListener导致奇怪的行为
当两个线程读取文件并标记CSV文件时,c ++ Boost多线程运行缓慢