c++thread-safetyboost-asio

Why does Boost emphasise thread-safety for distinct objects?


As per this official page, which says that (emphasis mine):

Thread Safety

Distinct objects: Safe.

Shared objects:

Safe, with the specific exceptions of the restart() and notify_fork() functions. Calling restart() while there are unfinished run(), run_one(), run_for(), run_until(), poll() or poll_one() calls results in undefined behaviour. The notify_fork() function should not be called while any io_context function, or any function on an I/O object that is associated with the io_context, is being called in another thread.

In general, when discussing thread safety, we pay attention to the behaviour of the same object read/written in mutiple threads.

Why is the thread-safety for distinct objects emphasised?


Solution

  • They talk to you in terms of the public interface of the library. What the library does internally they have to consider for the guarantess they provide you, but they need not tell you all the gory details.

    A silly counter example:

    struct bar {
        private:
            static int foo;  // defined elsewhere
        public:
            int do_something() const { 
                foo+=1;
                return foo;
            }
     };
    

    As a user I only need to know that do_something foos the bar, but how it is implemented internally is up to the implementation. In the documentation I'd expect that the library tells me that it is not safe to call do_something on two distinct objects concurrently.