What's the best way of ensuring valid object lifespan when using Boost.Asio?

前端 未结 2 1034
礼貌的吻别
礼貌的吻别 2021-02-07 17:15

Been playing a lot with Boost.Asio of late. I like the library a lot since it offers a fantastic way to squeeze performance out of today\'s multicore systems.

A questio

2条回答
  •  孤街浪徒
    2021-02-07 17:59

    That kind of thing isn't limited to Asio. I recently wrote a thread-pool class (using Boost::Thread) that had pretty much the same problem -- the threads would call the thread-pool class that created them to see what task they had to do next, using a plain pointer to it, and if the thread-pool class were destroyed with a child thread still running, the program would crash. I dealt with it by calling interrupt on each of the threads in the thread-pool destructor, then waiting for all of them to exit before letting the destructor return.

    If I understand your shared-pointer solution, it seems to be doing the same general thing -- ensuring that the item can't be destroyed until it's no longer needed. An aesthetically pleasing solution too. I don't see any better answer to this kind of problem.

提交回复
热议问题