c++rabbitmqamqpevent-looplibev

AMQP-CPP, libev > stop ev_loop from another thread


I use AMQP-CPP lib with libev backend. I try to create a class which will open a connection and do consuming. I want to run connection's loop in a worker thread in order not to block the main thread. That part of code looks like this

...
m_thread.reset(new std:thread([this]()
    {
        ev_run(m_loop, 0);
    }));
...

Then at some point I want to stop the loop. I have read that it is possible to do it with ev_break() function. However, it should be called from the same thread as ev_run() was called. More search showed that ev_async_send() function might do that, but I cannot figure out how.

How can I do it? Any ideas?


Solution

  • Here is an example:

    void asyncCallback(EV_P_ ev_async*, int)
    {
        ev_break(m_loop, EVBREAK_ONE);
    }
    
    void MyClass::stopLoop()
    {
        ev_async_init(&m_asyncWatcher, asyncCallback);
        ev_async_start(m_loop, &m_asyncWatcher);
        ev_async_send(m_loop, &m_asyncWatcher);
    
        m_thread->join();
    }
    
    // in the class async watcher should be defined
    ev_async m_asyncWatcher;
    

    By calling stopLoop() function from another thread it stops the loop that started from m_thread worker thread.