title: Libuv: protecting the event loop from concurrent accesses
body: <p>I would like to know what precautions are needed to be able to safely add callbacks to a <code>libuv</code> event loop from multiple threads in C++.</p>
  <p><strong>More details</strong></p>
  <p>I have some multi-threaded C++11 code that I want to modify to use make use of <code>libuv</code>'s network communication API. I do not want to create a new <code>libuv</code> event loop every time network communication is required (for that would use up resources). So I created a <code>libuv</code> loop in a separate thread (I prevent the loop from closing by registering a &quot;keep-alive&quot; timer). This event loop is currently passed to other threads using a <a href="https://stackoverflow.com/questions/1008019/c-singleton-design-pattern#1008289">singleton</a>. Callbacks are then registered (from other threads) while the loop is running.</p>
  <p>I am worried about concurrent accesses to the <code>libuv</code> event loop when registering new callbacks: when calling <code>uv_tcp_init</code> the loop is explicitly passed (rather, a pointer to the loop); when calling <code>uv_tcp_connect</code> the loop is not explicitly mentioned but a pointer to it is stored in the <code>uv_tcp_t</code> struct passed. I haven't checked whether any of the above-mentioned functions actually modify the loop, but my intuition is at least one of them must do to (otherwise, <code>libuv</code> couldn't keep track of active handles).</p>
  <p>My first thought was to add a <code>mutex</code> attribute to the singleton used to access the event loop and use it to prevent concurrent access to the event loop when calling any of the above functions:</p>
  <pre><code>EventLoop &amp; loop = EventLoop::get(); // Access the singleton
  {
      std::lock_guard&lt;std::mutex&gt; lock(loop.mutex_attribute);
      // Register callbacks, etc
  }
  </code></pre>
  <p>However, this does not protect the event loop from concurrent accesses between my thread (which successfully acquired the lock) and some <code>libuv</code> internal function (or a registered callback triggered by <code>libuv</code>) since the latter are not aware of my using a singleton to protect access.</p>
  <p>Should I be worried about said concurrent accesses? What steps may I take to mitigate the risks?</p>