在C ++中使用boost :: thread时,构造函数调用一次,但析构函数调用多次

时间:2019-04-13 06:58:51

标签: c++ multithreading boost constructor destructor

我正在使用boost库通过boost::thread类在c ++中创建线程。
我有以下课程,其中将void routine (int)定义为boost::thread例程:

A类:

class A
{
public:
    // Constructor
    A() { cout << "this is constructor" << endl; }

    void routine(int num)
    {
        for(int i = 0; i < num; i++)
        {
            // do stuffs
            cout << num + i << endl;
            Sleep(1000);
        }
    }

    // Destructor
    ~A() { cout << "this is destructor" << endl; }
};

main函数:

int main()
{
    A a;
    myThread = new boost::thread(&A::routine, a, 6);

    myThread->join();

    return 0;
}

main中,我创建一个A的对象,并且构造函数被调用一次,但是出了点问题。在这种情况下,destructor函数也应该仅被调用一次,但是它被调用了几次,并且得到以下结果:

this is constructor
this is destructor
this is destructor
this is destructor
this is destructor
this is destructor
this is destructor
this is destructor
6
7
8
9
10
11
this is destructor
this is destructor

有什么建议吗?

0 个答案:

没有答案