vendredi 2 janvier 2015

Deadlock using Boost.Asio and std::promise

I am using Boost 1.55 in Linux with gcc 4.8.


I commonly use boost::asio combined with std::promise/std::future but, sometimes, my program is deadlocked. This is a simplified program which shows that behaviour.



// Compile with: g++ -std=c++11 main.cpp -lpthread -lboost_system
#include <memory>
#include <functional>
#include <thread>
#include <future>
#include <cassert>

#include <boost/asio.hpp>

int main(int argc, char *argv[]) {
boost::asio::io_service ioService;
std::unique_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(ioService));
std::thread ioThread([&] () {
ioService.run();
});

for (int i=0; i<1000; i++) {
std::promise<bool> prom;
std::future<bool> fut = prom.get_future();
ioService.post([&prom] () {
prom.set_value(true);
});

assert(fut.get());
}

work.reset();
ioThread.join();
}


Am I correctly using the boost::asio::io_service? Debugging the program, the two threads are deadlocked calling the promise::set_value() and the future::get() methods. It seems that std::promise::set_value() uses the call_once() function that hangs when calling an internal Pthread function.


In Windows (using MSYS2), the program works OK. Also, if I substitute the Boost.Asio code with a std::thread based code (new thread per iteration), the example works OK.


Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire