【发布时间】: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;
}
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())何时停止并安全退出?谢谢。
【问题讨论】:
标签: c++ multithreading boost operators