以下是我们使用的示例。

class CustomThread
{
public:
    CustomThread(const std::wstring &id1)
    {
         t = new test(id1);
    }
    ~CustomThread();

    void startThread() {
        std::cout << "Do threading Operation here....." << std::endl;
    }

private:
    std::wstring id;
    test *t;
};


int main()
{
    for (int i = 1; i < 100; i++)
    {
        std::wstring id = L"1";
        CustomThread *ct = new CustomThread(id);

        boost::thread new_thread;
        new_thread = boost::thread(& CustomThread::startThread, ct);
        new_thread.detach();
    }

    // sleep for 100 second - to complete the thread task....
    sleep(100);
    return 0;

}

我创建了可分离线程,我想启动100个可分离线程。
在这里,我们执行new CustomThread 100次并分配内存。线程完成操作后会自动删除它吗?
您可以通过上面的示例指导如何释放分配的内存吗?

最佳答案

这里有几个问题。首先,由于CustomThread获取资源,因此需要遵循rule of three

现在,让我们看看您的设计。您动态分配了一个CustomThread,以便它不会在for循环的结尾被破坏,并且将在线程的整个生命周期内持续存在。这里的问题是您不知道确切何时删除该类,即使您确实没有,也没有指针来调用它的删除。您可以存储这些指针,但是仍然冒着可能在线程完成之前删除对象的风险。我们需要做的是以某种方式将线程和对象耦合在一起,以便我们知道线程完成运行后对象将被破坏。我们可以通过一个辅助函数来做到这一点。如果我们有

void thread_runner(std::wstring param)
{
    CustomThread ct(param);
    ct.startThread();
}

然后我们可以像这样在循环中调用此函数
for (int i = 1; i < 100; i++)
{
    std::wstring id = L"1";
    boost::thread new_thread;
    new_thread = boost::thread(&thread_runner, id);
    new_thread.detach();
}

现在,CustomThread对象会自动清除,您不必担心在何时何地调用delete(假设您的类具有正确的析构函数,或者您切换到RAII指针类型)。

关于c++ - 当可分离线程完成操作时取消分配内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45918366/

10-11 22:38
查看更多