title: Locking an object from being accessed by multiple threads - Objective-C
body: <p>I have a question regarding thread safety in Objective-C. I've read a couple of other answers, some of the Apple documentation, and still have some doubts regarding this, so thought I'd ask my own question.</p>
  
  <p>My question is <strong>three fold</strong>:</p>
  
  <p>Suppose I have an array, <code>NSMutableArray *myAwesomeArray;</code></p>
  
  <p><strong>Fold 1:</strong> </p>
  
  <p>Now correct me if I'm mistaken, but from what I understand, using <code>@synchronized(myAwesomeArray){...}</code> will prevent two threads from accessing the same block of code. So, basically, if I have something like:</p>
  
  <pre><code>-(void)doSomething {
      @synchronized(myAwesomeArray) {
          //some read/write operation on myAwesomeArray
      }
  }
  </code></pre>
  
  <p>then, if two threads access the <strong>same</strong> method at the <strong>same</strong> time, that block of code will be thread safe. I'm guessing I've understood this part properly.</p>
  
  <p><strong>Fold 2:</strong></p>
  
  <p>What do I do if <code>myAwesomeArray</code> is being accessed by multiple threads from different methods?
  If I have something like:</p>
  
  <pre><code>- (void)readFromArrayAccessedByThreadOne {
      //thread 1 reads from myAwesomeArray
  }
  
  - (void)writeToArrayAccessedByThreadTwo {
      //thread 2 writes to myAwesomeArray
  }
  </code></pre>
  
  <p>Now, both the methods are accessed by two different threads at the same time. How do I ensure that <code>myAwesomeArray</code> won't have problems? Do I use something like NSLock or NSRecursiveLock?</p>
  
  <p><strong>Fold 3:</strong></p>
  
  <p>Now, in the above two cases, <code>myAwesomeArray</code> was an iVar in memory. What if I have a database file, that I don't always keep in memory. I create a <code>databaseManagerInstance</code> whenever I want to perform database operations, and release it once I'm done. Thus, basically, different classes can access the database. Each class creates its own instance of <code>DatabaseManger</code>, but basically, they are all using the same, single database file. How do I ensure that data is not corrupted due to race conditions in such a situation?</p>
  
  <p>This will help me clear out some of my fundamentals.</p>