title: In Objective-C how do you mark a critical region?
body: <p>I have a simple scenario where a <code>NSTimer</code> is scheduled on a background thread to send a packet through a socket every so often. My main thread however, is responsible for destroying the timer and the socket.</p>
  
  <p>The destruction looks like this:</p>
  
  <pre><code>if (self.connected) {
      [self.pingTimer invalidate];
  
      if (self.socket != -1) {
          close(self.socket);
          self.socket = -1;
      }
  
      self.connected = NO;
  }
  </code></pre>
  
  <p>How can I ensure in Objective-C that once this section of code is entered, the scheduler isn't allowed to suspend this thread until the code section is over? In other words I want to make this code section atomic. </p>
  
  <p>My understanding is that the <code>@synchronized</code> directive is a high-level semaphore/mutex so to ensure atomicity of that code block, I would need to enclose the code block itself, as well as all the code which references either <code>self.connected</code>, <code>self.pingTimer</code> and <code>self.socket</code> in <code>@synchronized</code> directives. Am I correct in thinking this?</p>