title: How should I use epoll to read and write from the same FD
body: <h2>Environment</h2>
  
  <ul>
  <li>Linux x64</li>
  <li>Ubuntu 16.4</li>
  <li>C++</li>
  </ul>
  
  <h2>Use-case</h2>
  
  <ul>
  <li>Async IO ( epoll )</li>
  <li>A socket is used for both reading and writing</li>
  <li>Read &amp; Write operations and not in sync and are iteratively done on the socket</li>
  </ul>
  
  <h2>Sample flow</h2>
  
  <ol>
  <li>Setup socket (<em>EPOLL_CTL_ADD</em>)</li>
  <li>Start read (<em>EPOLL_CTL_MOD</em> + <strong>EPOLLIN</strong> | <em>EPOLLONESHOT</em>)</li>
  <li><strong>While waiting for data to be read</strong>
  
  <ul>
  <li><strong>[a]</strong> Write some data (<em>EPOLL_CTL_MOD</em> + <strong>EPOLLOUT</strong> | <em>EPOLLONESHOT</em>)</li>
  </ul></li>
  </ol>
  
  <h2>Problem description</h2>
  
  <ul>
  <li>At #2 above a <em>EPOLLIN</em> read operation is registered</li>
  <li>At #3.a, a <em>EPOLLOUT</em> write completion is registered <strong>before any data was read from the socket</strong></li>
  <li>Given the above, will the write completion operation @3.a cancel the pending read operation?
  
  <ul>
  <li>In other words, given the FD was initially called with (<em>EPOLL_CTL_MOD</em> + <strong>EPOLLOUT</strong>) that has no <em>EPOLLIN</em> set, will calling <em>EPOLL_CTL_MOD</em> + <em>EPOLLOUT</em> <strong>erase</strong> the previously registered <em>EPOLLIN</em> given data is not yet ready to be read ??</li>
  </ul></li>
  </ul>
  
  <h2>A possible workaround for the above</h2>
  
  <ul>
  <li>is to locally manage the req IO state by routing all read/write operations through the <em>epoll_wait</em> thread, hence, rather than calling <em>EPOLL_CTL_MOD</em> from an arbitrary thread, making sure it'll always be called from the same thread doing the <em>epoll_wait</em> where the FD IO state (<em>EPOLLOUT/EPOLLIN</em>) can be safely maintained.</li>
  <li>the problem w this workaround is that it req synchronizing all IO initiation through the <em>epoll_wait</em> thread, and that, result in an additional context switch that might adversely affect performance...</li>
  </ul>
  
  <h2>That`s what I am trying to figure out:</h2>
  
  <p>Is there any way to sync the Read/Write IO operations on a common FD w/o the need of syncing through the <em>epoll_wait</em> thread? is there any way of directly calling <em>EPOLL_CTL_MOD</em> w/o resetting the previous state? is there any <strong>thread safe way</strong> of adding <em>EPOLLOUT</em> on an FD that already has <em>EPOLLIN</em> set ?</p>