Re: Threads and synchronization
Re: Threads and synchronization
- Subject: Re: Threads and synchronization
- From: email@hidden
- Date: Thu, 10 Aug 2006 14:02:09 -0700
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@hidden
iChat & email: email@hidden
Jabber: email@hidden
Google Talk: email@hidden
http://homepage.mac.com/wadetregaskis/
-- Sed quis custodiet ipsos custodes?
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden