gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:57 25 4
gpt4 key购买 nike

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

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com