C++ boost线程在实例化两次时导致段错误

标签 c++ multithreading boost

我有一个在构建时运行后台任务的类(请参阅构造函数)。然后这个任务停止,当对象被销毁时,线程被加入到析构函数中:

// Foo.hpp -------------------------------
#include <boost/thread.hpp>
#include <boost/date_time/posix_time.hpp>

class Foo {
  boost::thread theThread;

  Foo();
  ~Foo();
  void bar() const;
}

// Foo.cpp -------------------------------
// This is the background task.
void Foo::bar() const {
  while (true) {
    try {
      // sleep for 1 minute.
      boost:this_thread_sleep(boost::posix_time::minutes(1));

      // do other stuff endlessly
    }

    // boost interrupt was called, stop the main loop.
    catch (const boost::thread_interrupted&)
    {
      break;
    }
}

// Instantiate background task
Foo::Foo()
    : theThread(&Foo::bar, this)
{
    // do other stuff
}

// Stop background task
Foo::~Foo() {
    theThread.interrupt()
    theThread.join();
}

现在当我有一个类的实例时这工作正常:

// main.cpp
Foo f;
// do other stuff with f

但是当我这样做时,我得到了一个段错误和一个中止的消息:

// main.cpp
Foo *f;
f = new Foo(); // causes seg fault
delete f;

为什么?

最佳答案

Xcode 给出错误:

Attempting to use a deleted function

Foo::Bar 不能用上面的语法调用 (&Foo::Bar),因为它不是静态函数。它有一个隐藏的 this 参数,导致签名不匹配。

更多相关信息: pthread function from a class

在初始化列表上使用成员函数也是不好的做法,行为是未定义的。此处引用:

Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point.

http://en.cppreference.com/w/cpp/language/initializer_list

以下作品:

   void bar(atomic_int*exit) {
    while (*exit) {
        // sleep for 1 minute.
        this_thread::sleep_for(std::chrono::seconds(2));

        // do other stuff endlessly

    }
}

class Foo {
    thread theThread;
    atomic_int _exit;

public:
   // Instantiate background task
    Foo(): _exit(1)
    {
        // do other stuff
        init();
    }
    void init()
    {
        theThread = std::thread (&bar,&_exit);
    }

    // Stop background task
    ~Foo() {
        _exit = 0;
        theThread.join();
    }
};

关于C++ boost线程在实例化两次时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786677/

相关文章:

C++ 如何根据某些条件在编译时删除类成员字段?

c++ - 几何、交集

multithreading - 我什么时候应该使用可升级锁?

c++ - Visual Studio 测试资源管理器找不到我的 Boost 测试

c++ - memcpy 和二维数组

c++ - 在仍然使用 cstdlib free 的同时在类中定义自定义 free()

c++ - 如何在嵌入式平台中管理不同 Pin-Out 板的代码以实现更好的 HAL 管理?

java - 如何在java中使函数阻塞?

python - 在 Uvicorn 中与多个工作线程一起使用多重处理(线程锁)

java - 关于Thread的逻辑问题