|
Boost Users : |
Subject: Re: [Boost-users] [ASIO] How to terminate a io_service inside a library.
From: Igor R (boost.lists_at_[hidden])
Date: 2009-04-10 07:55:44
> // Main io_service
> static boost::asio::io_service      io_service;
> static boost::scoped_ptr<boost::thread> io_service_thread;
> static boost::asio::io_service::work   work(io_service);
> static bool thread_started;
>
> EXTERN_C EUROATLIB_API MyObjHandl CALL GetMyObj()
> {
> Â if (!thread_started) {
> Â Â try {
> Â Â Â // run the IO service as a separate thread
> Â Â Â io_service_thread.reset(new boost::thread(
> boost::bind(&boost::asio::io_service::run, &io_service) ));
> Â Â Â thread_started = !thread_started;
> Â Â } catch (boost::thread_resource_error e) {
> Â Â Â // Failed to create the new thread
> Â Â Â return 0;
> Â Â }
> Â }
> Â // create the new object
> Â return new MyObj(io_service);
>
> };
> ----------------------------------------------------------
>
> Ok, now I need a way to stop the io_service thread when all MyObj are
> destroyed.
>
> In the clients I use:
>
> boost::scoped_ptr<MyObj> _devMyObj( GetMyObj() );
>
> How can I accomplish this in a right way?
I think the best way to do this is to remove the "work" object when
you want the io_service's thread(s) to end. So, if you wish this to
happen on last MyObj destruction, I guess the most intuitive approach
would be to create "work" on the heap and give each MyObj a shared_ptr
to it - then everything would happen automatically.
The only concern here is the fact that "work" is destroyed (and thus
detached from the io_service) in a thread other than io_service's one.
But since io_service is stated to be thread-safe, I guess it should be
safe.
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