Skip navigation.
 
mlRe: Threads and synchronization
FROM : wadeslists
DATE : Thu Aug 10 23:02:09 2006

Everyone has immediately jumped to locks.  Locking ensures mutual 
exclusion.  The goal of making your program thread safe is to reduce 
mutual exclusion, not just "deal with it".  The ideal multi-threaded 
program has no locks.

(locks imply serialization which implies less parallelism which 
defeats the purpose of multi-threading)

The best solution is to choose an algorithm that has implicit mutual 
exclusion - some data structures are particularly good for this, e.g. 
trees (yes, I know this is irrelevant to the original poster). 
Failing that, use data types that you can atomically modify (/usr/
include/libkern/OSAtomic.h is your friend).  Alignment is something 
to think about, but remember that malloc & calloc align to 16-byte 
boundaries (except when GuardMalloc is used) [1].  You do have to be 
a little more careful when using fields of structs, but it's not too 
tricky [2].

In any case, it sounds like the original poster could just use 
performSelectorOnMainThread:...

A key thing to remember is when passing data to new threads, the best 
and easiest time to do this is when the thread is created.  But keep 
in mind that the parameters to NSThread's 
detachNewThreadSelector:toTarget:withObject: are not automagically 
thread safe.  An easy way to ensure safety is to put your data into a 
collection that you pass as the parameter, then forget about in your 
original thread - the collection is retained by NSThread for the 
lifetime of the thread, and released when the thread exits.

To pass data back (e.g. thread state or task status), 
performSelectorOnMainThread:... is probably your friend, when dealing 
with UI updates.  You could use an atomic variable, but then you'd 
have to poll that in your main runloop, which is inefficient.

[1] http://developer.apple.com/technotes/tn2005/tn2130.html#TNTAG6
[2] http://developer.apple.com/documentation/DeveloperTools/
Conceptual/LowLevelABI/Articles/32bitPowerPC.html#//apple_ref/doc/uid/
TP40002438-DontLinkElementID_4

Wade Tregaskis

    ICQ: 40056898
    AIM, Yahoo & Skype: wadetregaskis
    MSN: <email_removed>
    iChat & email: <email_removed>
    Jabber: <email_removed>
    Google Talk: <email_removed>

    http://homepage.mac.com/wadetregaskis/

-- Sed quis custodiet ipsos custodes?

Related mailsAuthorDate
mlRE: Threads and synchronization John Stiles Aug 10, 20:17
mlRe: Threads and synchronization wadeslists Aug 10, 23:02
mlRe: Threads and synchronization Chris Kane Aug 17, 23:17