How to terminate a thread waiting for @synchronized object C
I have a code like this:
doDatabaseFetch {
...
@synchronized(self) {
...
}
}
and many objects calling doDatabaseFetch as the user is using the view.
My problem is that I have an operation (go to next view) that also requires fetching the database. My problem is it hits the same sync block and waits for it to rotate! Ideally, I would like this operation to kill all the threads waiting, or give this thread a higher priority so that it can execute immediately.
Apple says that
The recommended way to exit a stream is to let it exit normally from its entry point. Although Cocoa, POSIX, and Multiprocessing Services provide procedures for directly killing threads, the use of such routines is strongly discouraged.
So I don't think I should kill threads ... but how can I let them exit normally if they are waiting for a synchronized block? Do I have to write my own semaphore to handle this behavior?
Thanks! Nick.
a source to share
The first question to ask here is, do you need so much of the critical section to have so many threads waiting for input? What you are doing here is serializing parallel execution, i.e. Make your program single-threaded again (but slower). Reduce blocking area as much as possible, think about reducing contention at the application level, use appropriate synchronization tools (wait / signal) - you will find that you don't have to kill threads, almost never. I know this is very general advice, but it really helps to think like this.
a source to share
Generally, you cannot terminate a thread that is waiting for a synchronized block, if you want this behavior, you must use a timing wait and signal scheme so that the threads sleep while waiting and can be interrupted. Plus, if you use a timing out and signal scheme, every time the timeout expires, your threads have the option not to go back to sleep, but rather exit or take some other way (i.e. even if you don't want to terminate them) ...
Synchronized blocks are for unprotected locks, with an unprotected lock, the sync should be pretty close to noop, but once the lock becomes contested they are very detrimental to application performance, more or less simply because they are serializing your parallel program.
I'm not an Objective C expert by any means, but I'm sure there are some more advanced timing patterns like barriers, conditions, atoms, etc.
a source to share