ruslan.berliner
ruslan.berliner

Reputation: 121

How to avoid deadlock on @synchronized(self)?

I have some synchronization in my Objective-C project. The code looks like this:

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    //some code
    @synchronized(self) {    //at this line deadlocks
        //some code
    }
    //some code
}

and on this line (@synchronized), a deadlock always occurs. I can also tell that this delegate method is called very often.

How do I avoid such deadlocks?

Upvotes: 2

Views: 5110

Answers (2)

Roman Rader
Roman Rader

Reputation: 1236

You should review your classes design hardly. It shouldn't happen. If it happens, look at any critical sections (synchronized()) that locks the instance. One of them lock your instance forever. Or, maybe, you have cross lock (Method M1 locks A, and method M2 locks B, and they want to swap locking simultaneously ), it causes deadlock.

Upvotes: 3

justin
justin

Reputation: 104698

It means your lock from another thread never releases the lock acquired by @synchronized(self) -- you're probably waiting for something to finish, which is happening on another thread, trying to access the lock while held from another point. Look for this problem (if you pause, you will probably see waiting in the debugger on another thread). This also suggests your locks are held for long periods - only hold them for short periods if you want to use concurrency effectively.

Upvotes: 4

Related Questions