Re: Threading - How its done?
Re: Threading - How its done?
- Subject: Re: Threading - How its done?
- From: Chris Hanson <email@hidden>
- Date: Wed, 7 May 2008 23:45:20 -0700
On May 7, 2008, at 11:20 PM, Michael Vannorsdel wrote:
What is sounds like you're saying is something like:
const char * str = "Hello";
//thread 1
char bufferA[20]:
strncpy(bufferA, str, sizeof(bufferA));
//thread 2
char bufferB[20]:
strncpy(bufferB, str, sizeof(bufferB));
is unsafe and needs a lock?
What I'm saying is that in the general case you cannot assume that
just because you're reading you're "safe."
This gets people into a lot of trouble with Core Data, for example,
because simply accessing a property of an object will cause the
framework to do things that require state. You cannot thus simply
share Core Data managed objects between multiple threads without being
extremely careful to lock the object graph.
Similarly, if you are given an arbitrary object, unless it makes
explicit guarantees about the safety of doing so — whether as part of
the language standard, such as the example you give above, or via
documentation — you cannot assume that it is safe to access from
multiple threads at once.
For example, consider an immutable object that has a property which is
expensive to calculate. It could easily cache this value behind the
scenes. It's still immutable from its users' perspective, but it's
likely to behave incorrectly in some way if used from multiple threads
at once. And unless the object's class documentation says instances
are safe to share across multiple threads, you'd be violating its API
contract by doing so.
There is nothing that causes more bugs in writing threaded code than
assumptions about what is and isn't safe at any given instant. You
can't assume, you must know.
-- Chris
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden