Boost logo

Boost Users :

Subject: Re: [Boost-users] Is boost::asio::io_service thread safety?
From: Igor R (boost.lists_at_[hidden])
Date: 2012-04-07 14:56:40


> #include <iostream>
> #include <map>
> #include <boost/asio.hpp>
> #include <boost/bind.hpp>
> #include <boost/thread.hpp>
> #include <boost/date_time/posix_time/posix_time.hpp>
>
> namespace ba = boost::asio;
> namespace bp = boost::posix_time;
>
> typedef std::map<int, ba::deadline_timer*> timer_map;
>
> timer_map g_timers;
> boost::mutex g_timers_lock;
>
> ba::io_service g_ios;
>
> void on_timer(int id) {
>     {
>             boost::mutex::scoped_lock lock(g_timers_lock);
>             timer_map::iterator it = g_timers.find(id);
>             assert(it != g_timers.end());
>             g_timers.erase(id);
>     }
>
>     // std::cout << "delete timer " << id << std::endl;
> }
>
> int main(void) {
>     boost::thread trd(boost::bind(&ba::io_service::run, &g_ios));
>     trd.detach();
>
>     int count = 0;
>     for (;;) {
>             for (int i = 0; i < 100; i++) {
>                     ba::deadline_timer* pt = new
> ba::deadline_timer(g_ios, bp::seconds(1));
>                     pt->async_wait(boost::bind(&on_timer, count));
>
>                     boost::mutex::scoped_lock lock(g_timers_lock);
>                     g_timers.insert(std::make_pair(count++, pt));
>             }
>
>             usleep(20000);
>     }
>
>     return 0;
> }
>
>
> ==================================
> I know, I should lock the g_timers, but should I lock the g_ios? I
> mean these lines:
>
>    ba::deadline_timer* pt = new ba::deadline_timer(g_ios, bp::seconds(1));
>    pt->async_wait(boost::bind(&on_timer, count));
>
> Are thread safety? It reference the g_ios, and will it call
> g_ios.add_job(this_timer) ..etc.. ?

What is "add_job"? io_service doesn't have such a member function.
Anyway, it's safe to access io_service from multiple threads, as
documented:
http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/reference/io_service.html

By the way, instead of locking "g_timers.insert" you can just post
this function to io_service thread:
g_ios.post([]() {...do anything here});


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net