Re: Threads and synchronization
Re: Threads and synchronization
- Subject: Re: Threads and synchronization
- From: Chris Kane <email@hidden>
- Date: Thu, 17 Aug 2006 14:17:25 -0700
I would quibble a bit on this post from last week...
On Aug 10, 2006, at 2:02 PM, email@hidden wrote:
Everyone has immediately jumped to locks. Locking ensures mutual
exclusion.
Locking also ensures visibility of data changes. Generally,
individual processors are not compelled to inform other processors of
changes to data, nor are other processors compelled to pick it up
( into their L1 cache, say). The real trouble comes when some changes
are noticed and others are not, possibly resulting in what appears to
be an inconsistent state. The special instructions used by locking
also ensure timely and consistent visibility of changes.
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.
A good goal in making a program a better concurrent program is to
reduce mutual exclusion.
A multithreaded program may have no locks, because other techniques
have been used instead to avoid modifications to shared data
structures, not because no locks are necessary.
There are some advanced data structures and techniques for lockless
concurrency, but most of them require careful and sophisticated
coding, impose various restrictions (e.g. in some cases, can't free
memory), and can produce other forms of performance issues. For
example of the latter, lockless algorithms using "atomic add" or
"compare-and-swap" operations may induce more bus synchronizations
[which are expensive] getting through a chunk of code than if you'd
just put a simple lock around the whole thing.
(locks imply serialization which implies less parallelism which
defeats the purpose of multi-threading)
The problem you are getting at is with >contended< locks, which cause
threads to block in their execution. People shouldn't worry about
uncontended locking. And while contention on a lock can be solved
with sophisticated techniques which eliminate the lock, there are
other simpler techniques that often solve the problem just as well
(for example, reorganizing the code to move some outside the lock, or
unlocking the lock while doing an expensive operation then relocking
it -- with some additional checks to see if its still valid to
continue, or avoiding the contention by deciding that a particular
threads shouldn't be looking at that data after all or other such high-
level structural changes).
Chris Kane
Cocoa Frameworks, Apple
_______________________________________________
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