asio high_resolution_timer async_wait中的分段错误

时间:2016-03-16 14:19:21

标签: c++ c++11 segmentation-fault boost-asio

我已经实现了一个优先级为asio examples的任务队列和一个使用此队列的计时器类。这是代码:

priority_task_queue.h

var data = [{ a: 1, b: "apples" }, { a: 3, b: "apples" }, { a: 4, b: "apples" }, { a: 1, b: "bananas" }, { a: 3, b: "bananas" }, { a: 5, b: "bananas" }, { a: 6, b: "bananas" }, { a: 3, b: "oranges" }, { a: 5, b: "oranges" }, { a: 6, b: "oranges" }, { a: 10, b: "oranges" }],
    result = function (array) {
        var r = [], o = {};
        array.forEach(function (a) {
            if (!(a.b in o)) {
                o[a.b] = r.push(a) - 1;
                return;
            }
            if (r[o[a.b]].a < a.a) {
                r[o[a.b]] = a;
            }
        });
        return r;
    }(data);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

priority_task_queue.cpp

class handler_priority_queue
{
private:
    class queued_handler{
    private:
        size_t _priority;
        std::function<void()> _function;
    public:
        queued_handler(size_t p, std::function<void()> f): _priority(p), _function(f){}
        friend bool operator<(const queued_handler& a, const queued_handler& b){
            return a._priority < b._priority;
        }
        void operator()() {
            _function();
        }
    };
    std::priority_queue<queued_handler> _handlers;

public:
    // A generic wrapper class for handlers to allow the invocation to be hooked.
    template <typename Handler> class wrapped_handler
    {
        private:
            handler_priority_queue& _queue;
            size_t _priority;
            Handler _handler;

        public:
            handler_priority_queue& queue() {return _queue;}
            size_t priority() {return _priority;}

            wrapped_handler(handler_priority_queue& q, size_t p, Handler h)
                : _queue(q), _priority(p), _handler(h){}


            template <typename ...Args>
            void operator()(Args&&... args){
                _handler(std::forward<Args>(args)...);
            }
    };
    template <typename Handler> wrapped_handler<Handler> wrap(size_t priority, Handler handler){
        return wrapped_handler<Handler>(*this, priority, handler);
    }
    void add(size_t priority, std::function<void()> function);
    void execute_all();
    void execute_one();
    bool empty();
};

// Custom invocation hook for wrapped handlers.
template <typename Function, typename Handler>
void asio_handler_invoke(Function f, handler_priority_queue::wrapped_handler<Handler>* h){
    h->queue().add(h->priority(), f);
    std::cout<<"LLAMANDO AL INVOKE"<<std::endl; //BORRAR!!
}

class C_priority_task_queue{

    private:
        asio::io_service& _io;
        handler_priority_queue _pri_queue;

    public:
        template <typename Handler> handler_priority_queue::wrapped_handler<Handler> wrap(int priority, Handler handler){
            return _pri_queue.wrap(priority, handler);
        }

        explicit C_priority_task_queue(asio::io_service& io): _io(io){}
        C_priority_task_queue(C_priority_task_queue const&) = delete;
        C_priority_task_queue& operator =(C_priority_task_queue const&) = delete;

        asio::io_service& io() {return _io;}
        void run();
};

base_timer.h

void handler_priority_queue::add(size_t priority, std::function<void()> function){
    _handlers.push(queued_handler(priority, function));
}

void handler_priority_queue::execute_one(){
    if(!_handlers.empty()){
        queued_handler handler = _handlers.top();
        handler();
        _handlers.pop();
    }
}

bool handler_priority_queue::empty(){
    return _handlers.empty();
}

void C_priority_task_queue::run(){
    while (_io.run_one())
    {
        _io.poll();
        while(!_pri_queue.empty())
        {
            _io.poll();
            _pri_queue.execute_one();
        }
    }
}

base_timer.cpp

class C_timer {
    private:
        asio::high_resolution_timer _timer;
        uint8_t _timer_id; 
        C_priority_task_queue& _prio_queue;


    void timer_handler_internal(const asio::error_code& e, uint8_t timer_id, const uint64_t sched_time);
    virtual void timer_handler(const uint64_t sched_time)=0;

    public:
        size_t _priority;
        explicit C_timer(C_priority_task_queue& prio_queue, size_t priority);
        virtual ~C_timer();

        void set_timer(uint64_t sched_time);
        int cancel();
};

测试类

C_timer::C_timer(C_priority_task_queue& prio_queue, size_t priority):
        _timer(prio_queue.io()), _timer_id(0), _prio_queue(prio_queue), _priority(priority){}

C_timer::~C_timer(){}

void C_timer::set_timer(uint64_t sched_time){
    ++_timer_id;

    _timer.expires_at(std::chrono::time_point<std::chrono::high_resolution_clock>(std::chrono::milliseconds(sched_time)));
    _timer.async_wait(_prio_queue.wrap(_priority, std::bind(&C_timer::timer_handler_internal, this,
                      std::placeholders::_1/*error*/, _timer_id, sched_time)));
}

int C_timer::cancel(){
    ++_timer_id;
    return _timer.cancel();
}

void C_timer::timer_handler_internal(const asio::error_code& e, uint8_t timer_id,
                                               const uint64_t sched_time){
    if(e==asio::error::operation_aborted || timer_id != _timer_id){
        return;
    }
    timer_handler(sched_time);
}

问题是如果我执行这个:

class C_timer_test: public C_timer{
    private:
        int _period;

        virtual void timer_handler(const uint64_t sched_time) override{
            std::cout<<"timer fired"<<std::endl;

            uint64_t current_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
            set_timer(current_time + _period);
        }

    public:
        C_timer_test(C_priority_task_queue& prio_queue, int priority, int period):C_timer(prio_queue, priority), _periodo(period){}
        virtual ~C_timer_test(){}
        void run(uint64_t delay=0){
            uint64_t time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
            set_timer(time + delay);
        }
};

我遇到了分段错误。

但是,如果我执行以下代码,它可以正常工作:

int main()
{
    asio::io_service io;
    C_priority_task_queue prio_queue(io);
    asio::io_service::work w(io);

  C_timer_test ti1(prio_queue, 0, 2000);
  ti1.run();
  prio_queue.run();

  return 0;
}

两段代码之间的唯一区别在于第二个主要内容我添加了以下行int main() { asio::io_service io; C_priority_task_queue prio_queue(io); asio::high_resolution_timer _timer1(io); asio::io_service::work w(io); C_timer_test ti1(prio_queue, 0, 2000); ti1.run(); prio_queue.run(); return 0; } ,我没有在任何地方使用过。

调试程序我发现该行中的信号正在上升: 文件asio::high_resolution_timer _timer1(io);

中的func_(&owner, this, ec, bytes_transferred);

我正在使用asio版本1.10.6。

有什么可能发生的事情?

来自gdb的回溯:

task_io_service_operation.hpp

这里有MakeFile:

gdb ./main 
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
This GDB was configured as "i686-linux-gnu".
(gdb) r
[libthread_db enabled]
Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x0805f0d4 in ?? ()
(gdb) backtrace 
#0  0x0805f0d4 in ?? ()
#1  0x080529fb in asio::detail::task_io_service::do_run_one (this=0x805f030, lock=..., this_thread=..., ec=...) at /src/cpp/external_lib/asio/include/asio/detail/impl/task_io_service.ipp:371
#2  0x080526ce in asio::detail::task_io_service::run_one (this=0x805f030, ec=...) at /src/cpp/external_lib/asio/include/asio/detail/impl/task_io_service.ipp:169
#3  0x08052c68 in asio::io_service::run_one (this=0xbffff08c) at /src/cpp/external_lib/asio/include/asio/impl/io_service.ipp:71
#4  0x08051f32 in C_priority_task_queue::run (this=0xbffff094) at priority_task_queue.cpp:19
#5  0x08049ac3 in main () at main.cpp:46

更新

我的调查,我发现如果我在.h中定义base_timer成员(基本上是asio :: high_resolution_timer)初始化,代码运行正常,但如果我在.cpp中执行此操作,代码会崩溃。< / p>

我的意思是,

TARGET=main
SOURCES=  main.cpp base_timer.cpp  priority_task_queue.cpp
SOURCE_DIR=.
INCLUDE_LIB= -L/src/cpp/libcore
INCLUDE_DIR=-I/src/cpp/external_lib/asio/include \
             -I/src/cpp/libcore/include
INSTALL_DIR=.
LIB=-pthread
CXX=g++
CFLAGS=-Wall -fexceptions -fpermissive -std=c++11 -DASIO_STANDALONE
CFLAGS_DEBUG = -g3 -DDEBUG
OBJDIR_DEBUG=obj
BINDIR_DEBUG=.
OBJECTS_DEBUG:= $(addprefix $(OBJDIR_DEBUG)/,$(SOURCES:.cpp=.o))

all: debug

$(OBJDIR_DEBUG)/%.o: $(SOURCE_DIR)/%.cpp
    @test -d $(OBJDIR_DEBUG) || mkdir -p $(OBJDIR_DEBUG)
    $(CXX) $(CFLAGS) $(CFLAGS_DEBUG) $(INCLUDE_DIR) -c $< -o $@

debug: $(OBJECTS_DEBUG)
    @test -d $(BINDIR_DEBUG) || mkdir -p $(BINDIR_DEBUG)
    $(CXX) -o $(BINDIR_DEBUG)/$(TARGET) $^ $(INCLUDE_LIB) $(LIB)
.h中的

可以,但是

explicit C_timer(C_priority_task_queue& prio_queue, size_t priority):
        _timer(prio_queue.io()), _timer_id(0), _prio_queue(prio_queue), _priority(priority){}
.cpp中的

失败

2 个答案:

答案 0 :(得分:0)

除了“非自然的”玩弄时间(时间点或持续时间,选择一个!),代码看起来没问题。我无法重现任何失败(GCC,linux):

<强> Live On Coliru

如果添加随机变量会使问题出现/消失,您应该考虑未定义的行为,使用静态分析,valgrind / purify / ...以及代码审查以找到您的罪魁祸首。 Valgrind,ASAN和UBSAN在我的电脑上跑得很干净

  

@谢谢你的努力。不同之处在于,如果我将每个代码放入一个文件main.cpp中,它会运行,但如果我分成几个文件,问题仍然存在。另一方面,如果我在main.cpp中实例化一个high_resolution_timer对象,无论该位置(在main(内部),在从不调用的单独函数中,...)它都会运行,但如果没有它,则会引发分段错误。

这很棒:您已找到UB的潜在源:查看静态变量或非ODR安全的内联函数的使用。 (仔细检查所有翻译单元是否使用相同的编译器标志)。

此外,请注意 UB UNDEFINED ,因此添加不相关的_timer1会改变明显的行为(无需更改 UB的来源)同样的事情可以让出现来工作。

它在我的机器上运行干净的事实告诉你,这必须是特定于平台的UB来源

答案 1 :(得分:0)

问题是我一直在使用该库的1.10.2版本,似乎有一个错误。

我已更新到最新版本1.10.6,现在运行正常。