C ++ Boost多线程奇怪的行为

时间:2018-03-10 18:25:23

标签: c++ multithreading boost operators

我正在关注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;
}

enter image description here 但是,如果我将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())何时停止并安全退出?感谢。

enter image description here

1 个答案:

答案 0 :(得分:0)

boost::thread在销毁时不会停止执行。 std::thread不允许您执行此操作,如果您在未加入主题的情况下销毁该主题,则会调用std::terminate

您需要将t.join()添加到main()方法的末尾。

void operator () ()是没有参数的()运算符,第一个()是运算符的名称,第二个()是参数列表。例如,带参数的可调用类看起来像:

struct s
{
   void operator ()( int p ) {};
}