title: Shared memory with "mutex" and NSCondition on iPhone
body: <p>What I need to do : 
    In order to avoid global variable, I have a Singleton class containing an array. This array will be accessed by two different threads :<br>
  - 1) the first one will be the main thread and will have to add objects into this NSMutableArray from time to time.<br>
  - 2) another thread is looping (while TRUE) and try to empty the array (when it contains something) </p>
  
  <p>My idea was (and what i did so far): 
  in my singleton class, i have my NSMutableArray (<code>list</code>) and a NSCondition (<code>conditionLock</code>).<br>
  <b>What my main thread is doing is : </b> </p>
  
  <pre><code> [[sharedSingleton conditionLock] lock];  
   [[sharedSingleton list] addObject:obj];  
   [[sharedSingleton conditionLock] signal];  
   [[sharedSingleton conditionLock] unlock]; 
  </code></pre>
  
  <p>I want to block the object so that it doesn't get empty when I try to put objects in it. (shared memory protection). Once the object has been put into the array, I signal the other thread. If i understood it right, this is kind of increasing a counter, like with a semaphore right ? The signal is telling the other Thread "there is an object, go on".</p>
  
  <p><b>What the second thread is doing:</b></p>
  
  <pre><code>while (YES) {  
      [[sharedRequest conditionLock] lock];  
      [[sharedRequest conditionLock] wait];  
      RequestLauncher * req = [[RequestLauncher alloc] initWithGenericsObject:[[sharedRequest list] objectAtIndex:0]];  
      [req performSelectorOnMainThread:@selector(Launch) 
                                 withObject: nil
                              waitUntilDone:YES];  
      [[sharedRequest list] removeObjectAtIndex:0];  
      [[sharedRequest conditionLock] unlock];
  }
  </code></pre>
  
  <p>So i guess my problem is that I Lock and then wait for the signal, but all Apple example are in that order. 
  This code seems to work when I'm adding one object in my main thread. However, when I want to add more than one, it gets blocked around the Lock.</p>
  
  <p><b>EDIT</b>
  I tried something different, but the behavior was not the one expected : 
  <code><br>
  while (YES) {<br>
      [[sharedRequest conditionLock] lock];<br>
      [[sharedRequest conditionLock] wait];<br>
      GenericsObject * obj = [[sharedRequest list] objectAtIndex:0];<br>
      [[sharedRequest list] removeObjectAtIndex:0];<br>
      [[sharedRequest conditionLock] unlock];<br>
      RequestLauncher * req = [[RequestLauncher alloc] initWithGenericsObject:obj];<br>
      [req performSelectorOnMainThread:@selector(Launch) withObject: nil waitUntilDone:YES];<br>
  }
  </code>
  Like this, I was unlocking the NSMutableArray so that the mainThread was able to add objects.</p>