如何让std :: thread在执行其成员函数后自动删除对象

问题描述 投票:2回答:2

我想要实现一个cmmand类,它在另一个线程中做一些工作,我不想让用户手动删除该对象。我的command类是这样的:

class Cmd {
 public:
  void excute() {
    std::cout << "thread begins" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));  // do some work
    std::cout << "thread ends" << std::endl;
  }

  void run() {
    // I want std::unique_ptr to delete 'this' after work is done,but does't work
    std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
    td.detach();
  }

  // test if this object is still alive
  void ok() { std::cout << "OK" << std::endl; }
};

我这样使用它:

int main() {
  Cmd *p = new Cmd();
  p->run();

  // waiting for cmd thread ends
  std::this_thread::sleep_for(std::chrono::seconds(3));

  p->ok();  // I thought p was deleted but not

  return 0;
}

在评论中,cmd线程完成后对象仍然存在,我想知道如何实现这样的功能。

编辑

cmd的用户不知道cmd什么时候会完成,所以流动的用例将导致UB。

std::unique_ptr<Cmd> up(new Cmd);  // or just Cmd c;
up->run();
// cmd will be deleted after out of scope but cmd::excute may still need it

关闭

我在测试时犯了一个错误,事实上在线程结束后删除了对象。使用额外的成员变量int i进行后续测试更清楚。

#include <functional>
#include <iostream>
#include <stack>
#include <thread>

using namespace std;

class Cmd {
 public:
  ~Cmd() { std::cout << "destructor" << std::endl; }

  void excute() {
    std::cout << i << " thread begins" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));  // do some work
    std::cout << i << " thread ends" << std::endl;
  }

  void run() {
    // I want std::unique_ptr to delete 'this' after work is done,but it seems
    // not working
    std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
    td.detach();
  }

  // test if this object is still alive
  void ok() { std::cout << i << " OK" << std::endl; }

  int i;
};

int main() {
  Cmd *p = new Cmd();
  p->i = 10;
  p->run();

  // waiting for cmd thread ends
  std::this_thread::sleep_for(std::chrono::seconds(3));

  p->ok();  // I thought p was deleted but not

  return 0;
}

以下输出证明该对象已删除。

10 thread begins
10 thread ends
destructor
-572662307 OK

但正如一些善良的人所说,这不是一个好的设计,尽可能避免它。

c++ memory-management stdthread
2个回答
1
投票

您可以使用std::future来表示状态,而不是线程。然后,您可以等待任务完成,或完全忽略未来。

#include <future>
#include <chrono>
#include <mutex>
#include <iostream>

class Cmd {
public:
    std::future<void> run() {
        std::lock_guard<std::mutex> lock(startMutex);
        if (started) {
            throw std::logic_error("already started");
        }
        started = true;

        // Take copies here, so that it doesn't matter if Cmd is destroyed
        int i_ = i;
        return std::async(std::launch::async, [i_]() {
            std::this_thread::sleep_for(std::chrono::seconds(2));
            std::cout << i_ << std::endl;
        });
    }

    int i = 0;

private:
    std::mutex startMutex;
    bool started = false;
};

int main() {
    auto p = std::make_unique<Cmd>();
    p->i = 10;
    auto f = p->run();
    p.reset();

    // Do some other work

    // Wait for the task to finish (or use f.get() if there is no need to
    // do some other work while waiting)
    if (f.valid()) {
        std::future_status operation;
        do {
            // Do some other work

            operation = f.wait_for(std::chrono::milliseconds(1));
        } while (operation != std::future_status::ready);
    }
}

0
投票

有两种方法可以自动删除动态创建的内存。

  1. 在客户端代码(主函数)中,你应该使用像unique_pointer这样的智能指针,这样一旦对象离开作用域,它将自动在unique_poiter析构函数中释放
  2. 你可以创建自己的smart pointer,它将是Cmd类的包装。并且必须使一些运营商超载。这个智能指针也将在析构函数中处理动态分配的内存。客户端代码应在动态创建Cmd对象时使用此智能指针。
© www.soinside.com 2019 - 2024. All rights reserved.