Re: Thread crashing problem
Re: Thread crashing problem
- Subject: Re: Thread crashing problem
- From: Jason Foreman <email@hidden>
- Date: Mon, 22 Dec 2008 10:59:50 -0600
On Dec 22, 2008, at 9:42 AM, Ken Tozier wrote:
Problem is, I'm a thread noob so have no idea which type of lock is
right for my situation. As to @synchronized, Robert Marini seemed to
suggest that that was a Leopard-pnly solution. This app has to work
on Tiger as well.
As a self professed "thread noob," make sure you've read this:
http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/Multithreading/
You might also be well served to do some research on pthreads, and
make sure you understand the synchronization primitives such as
semaphores and mutexes. You'll only end up doing bodily harm to
yourself and others if you don't understand the basics of threading at
a fundamental level.
After you've read those, you should realize that, as Kyle points out,
your code does not determine when it is safe to run. Instead it
should acquire a lock to tell the threading system that it wants to do
something (e.g. modify a data structure), and the threading library
will let your code run when it is safe to do so (it can acquire the
lock). @synchronized is essentially some syntax sugar that wraps a
block of code with a lock, so that only one thread can be executing
that code at a time.
Any code which modifies a shared data structure should be protected by
a lock. The lock is there to ensure that only one thread can modify
the data at a time. So all your code that modifies the data structure
should use a (the same) lock. So to answer one of your questions:
yes, make the lock a property of the class--you need to use *the same*
lock in each method to ensure proper synchronization.
Also, you needn't determine if the lock is locked. Look at the docs
for the NSLocking protocol. You'll want to call -[NSLock lock], which
will block the calling thread until the lock can be acquired. Your
concerns about multiply calling tryLock are only applicable to
acquiring a lock recursively, i.e. acquiring the lock again on a
thread which already holds it.
This is a very simplified account however, so please make sure you
understand what you're doing and why--don't just take my word for it
(I could be full of it). Threaded programming can be hard and is very
easy to get wrong.
Good luck!
Jason
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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