objective c - How do I check if an object is being @synchronized -
sometimes wrote following code synchronized routine:
@synchronized(objtobesync){ .... }
when 2 threads try access sync block @ same time, 1 block others, until 1 exits sync block.
however, don't want 1 blocks other, others check if object being synchronized, , other thing have sth this:
@synchronized(objtobesync){ _isbeingsync = yes; ... _isbeingsync = no; }
_isbeingsync
additional var on checking if objtobesync being sync. other threads check _isbeingsync
before continue work. , question objc provide sth check objtobesync directly not introduce additional var mark down status.
the compiler translates @synchronized(objtobesync) { ... }
into
callq _objc_sync_enter ... callq _objc_sync_exit
and objective-c runtime source code (objc-sync.mm, objc-os.mm, objc-lockdebug.mm, objc-os.h) 1 can see these functions
pthread_mutex_lock(m->mutex); ... pthread_mutex_unlock(m->mutex);
where m->mutex
pthread_mutex_t
pthread_mutex_recursive
attribute associated object objtobesync
, using cache internal runtime.
so direct answer question is: no, there no public api "locked" status of object, , accessing internal mutex seems impossible me.
therefore, should use different locking mechanism if have requirement, e.g. posix mutex lock, nslock
or nsrecursivelock
. these locks have "try" method can used aquire lock, or fail without blocking.
see "threading programming guide: synchronization" overview.
note @synchronized
(in contrast other locking mechanisms) implicitly adds exception handler block mutex released if exception thrown.
also @synchronized
recursive lock, i.e. same thread can enter protected code without blocking. if relevant code, have use nsrecursivelock
or posix mutex lock "recursive" attribute.
note using simple instance variable _isbeingsync
purpose subject race conditions , not work safely.
Comments
Post a Comment