title: Linux timer pending signal
body: <p>I am creating linux timer using timer_create with SIGEV_THREAD parameter.</p>
  
  <p>Sometimes callback is called after I disarm timer and delete it. This causes segfault, because it tries to access deleted resources.</p>
  
  <p><a href="http://man7.org/linux/man-pages/man2/timer_delete.2.html" rel="nofollow noreferrer">http://man7.org/linux/man-pages/man2/timer_delete.2.html</a></p>
  
  <p>Linux manual says</p>
  
  <blockquote>
    <p>timer_delete() deletes the timer whose ID is given in timerid.  If
    the timer was armed at the time of this call, it is disarmed before
    being deleted. <strong>The treatment of any pending signal generated by the
    deleted timer is unspecified.</strong></p>
  </blockquote>
  
  <p>That basically means that I don't really know whether the callback will be called or not and I don't have a way neither to cancel it nor to force pending signal to deliver before I clean up the resources.</p>
  
  <pre><code>class timer_wrapper
  {
  private:
      std::function&lt;void()&gt; callback_;
      timer_t timer_;
  
      static void timer_callback(sigval_t val)
      {
          static_cast&lt;timer_wrapper*&gt;(val.sival_ptr)-&gt;callback_();
      }
  public:
      timer_wrapper(std::function&lt;void()&gt; callback, uint32_t interval_sec)
          : callback_(std::move(callback))
      {
          struct sigevent ev;
          ev.sigev_notify = SIGEV_THREAD;
          ev.sigev_signo = 0;
          ev.sigev_value.sival_ptr = this;
          ev.sigev_notify_function = &amp;timer_wrapper::timer_callback;
          ev.sigev_notify_attributes = 0;
          timer_create(CLOCK_REALTIME, &amp;ev, &amp;timer_);
  
          struct itimerspec spec = {{0, 0}, {interval_sec, 0}};
          timer_settime(timer_, 0, &amp;spec, nullptr);
      }
  
      ~timer_wrapper()
      {
          timer_delete(timer_);
      }
  };
  </code></pre>
  
  <p>If timer_wrapper goes out of scope I expect callback will not get called anymore, however it's called sometimes and according to man this is expected behavior.</p>
  
  <p>What is the suggested way to resolve this issue?</p>