我有一些代码可以动态分配一个新的 std::thread
来自 C++11 <thread>
标题,像这样:
std::thread *th = new thread( /* my args */);
一段时间后,我调用加入:
th->join();
既然我动态分配了线程,我还需要调用delete th;
吗?释放内存?如果我这样做,我还需要打电话吗 join()
第一?
最佳答案
为避免内存泄漏,您需要:加入
一个正在运行的线程,并确保它已被破坏/删除(让它超出堆栈分配的范围 std::threads
或为 std::thread*
显式调用 delete。
参见 thread::~thread在 cppreference 中:
A thread object does not have an associated thread (and is safe to destroy) after:
- it was default-constructed
- it was moved from
- join() has been called
- detach() has been called
因此,无法安全地销毁未加入的线程。
join()
ed std::thread
仍会占用一些内存。因此,如果它在堆上,您需要确保它被正确释放。
关于c++ - 调用 join 后删除 std::thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090299/