开发者

Pthread RWLock on MAC Deadlocking but not on Linux?

开发者 https://www.devze.com 2023-01-21 05:57 出处:网络
I\'ve been experimenting with rwlock\'s on Mac and am experiencing something that seems to me shouldn\'t be happening. There\'s some weird combination of using read/write locks with recursive read loc

I've been experimenting with rwlock's on Mac and am experiencing something that seems to me shouldn't be happening. There's some weird combination of using read/write locks with recursive read locks that is deadlocking, but shouldn't be.

I posted the code on pastebin because it's more than just a snippet. The way this code is written shouldn't deadlock, and indeed doesn't when running on linux. Why does 开发者_高级运维this deadlock on a mac?

http://pastebin.com/Ui9iS1ke

Any ideas?


See the bug I reported with apple.

https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa/7/wo/0blX77DJS8lBTTxVnTsNDM/5.83.28.0.13


Here's the open radar bug.

http://openradar.appspot.com/8588290


Aaron: I just ran into this. I found that one can workaround this by using thread local storage. Create a wrapper around the rwlock that increments a thread local key:

@interface ReadWriteLock : NSObject {
    pthread_key_t readKey;
    pthread_key_t writeKey;
    pthread_rwlock_t rwLock;
}

-(void)lockRead;
-(void)unlockRead;

-(void)lockWrite;
-(void)unlockWrite;

@end

Then increment the readKey using pthread_setspecific when you call lockRead, decrement it when you call unlockRead, only rd_lock when the key goes from 0 to 1 and only rw_unlock when the key goes from 1 to 0. Copy this for the writeLock logic.

Since the pthread_setspecific and pthread_getspecific are thread-local, you don't need to lock around access to these. Make sure to call the appropriate pthread creation / initialization functions in init, and make sure to dispose of all of the pthread_* members in dealloc.

Unfortunately I can't give you the full source to my solution, but the above method works ( I've tested it heavily ).

0

精彩评论

暂无评论...
验证码 换一张
取 消