Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you're talking Cocoa, the mutex functionality there is provided by <code>NSLock</code> and <code>NSRecursiveLock</code>.</p> <p>In order to properly protect non-atomic resource, you need these mutexes, lest multiple threads may try to change the data at the same time (leading to corruption) or use the data in a half-changed state (leading to invalid data).</p> <p>Your code would look something like this:</p> <pre><code>static NSLock session_id_lock; static unsigned int session_id = 1000; - (int) generateSessionID{ int new_id; [myLock lock]; new_id = session_id++; [myLock unlock]; return new_id; } </code></pre> <p>If you're not using Cocoa (or what little Cocoa programming I remember from my brief interlude with an iMac is so dimly remembered that it's near useless), just use the concept, translating it to whatever language or framework you have:</p> <ul> <li>lock the mutex before using or changing a protected resource.</li> <li>use or change the resource.</li> <li>unlock the mutex.</li> <li>bonus advice 1: lock the mutex as late as possible and unlock it as soon as possible.</li> <li>bonus advice 2: only lock what you need so you avoid unnecessary delays.</li> </ul> <p>Explaining that last point some more: if you synchronise on <code>self</code> for two totally unrelated things (say a session ID and a user ID), they will block each other despite the fact that it's not necessary to do so. I would prefer two separate mutexes to keep the granularity low.</p> <p>Of course, if you only have a mutex on the session ID alone (but see below for caveat), feel free to use <code>synchronized(self)</code> but I'd prefer to do it my way so I wouldn't get caught out adding another protected resource later.</p> <p>In any case (this is the caveat mentioned), you will probably find that synchronising on <code>self</code> would not adequately protect a static variable, which would be shared across multiple objects. The mutex should belong to the <em>data</em> rather than whatever is using it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload