Weak reference variable is thread safe

Source: Internet
Author: User

1, before the arc appears, Objetive-c's memory management needs to perform the Release&retain operation manually, these greatly increased the code to write the difficulty, simultaneously brings many crash.

At the same time a large number of delegate is Unretain, if you forget to dealloc in the active set to empty, will bring the hidden danger of the wild pointer. Because Dealloc is a thread-unsafe method

Under the MRC environment, if an object is being released in one thread, the object receives a notification on another thread, which is most likely to bring crash,

This depends on whether the memory of the object accessed in the method being executed is destroyed.

2, Arc appeared after the weak modifier, reducing the probability of the wild pointer, while the Dealloc method has been modified, the user does not need to actively call [Super Dealloc], by the compiler inserted.

At the same time the compiler inserted a Cxx_dealloc method, this method really frees the object to hold the variable, the Dealloc method can only be counted as a callback to be released, then the arc below the dealloc is how to execute it.

3, Dealloc method of implementation

1. An object executes the release method, the reference count is reduced by 1 and becomes 0

2. Call the Dealloc method of the object

3, the object Dealloc method execution finished calling the Dealloc method of the parent class

4, call the Dealloc method of NSObject

5, NSObject's Dealloc method executes _objc_rootdealloc (self);

6. Call Object_dispose () in _objc_rootdealloc

7. Call Objc_destructinstance () in Object_dispose

8. Objc_destructinstance Call Objc_clear_deallocating

  

1 void*objc_destructinstance (IDobj)2 {3     if(obj) {4Class Isa_gen =_object_getclass (obj);5class_t *isa =newcls (Isa_gen);6 7         //Read all of the flags at once for performance.8         BOOLCxx =hascxxstructors (ISA);9         BOOLASSOC =! USEGC &&_class_instanceshaveassociatedobjects (Isa_gen);Ten  One         //This order is important. A         if(cxx) object_cxxdestruct (obj); -         if(Assoc) _object_remove_assocations (obj); -  the         if(!usegc) objc_clear_deallocating (obj); -     } -  -     returnobj; + } - voidObjc_clear_deallocating (IDobj) + { A assert (obj); atASSERT (!USEGC); -  -Sidetable *table = sidetable::tableforpointer (obj);/** * * * **/ -  -     //clear any weak table items -     //Clear extra retain count and deallocating bit in     //(Fixme warn or abort if extra retain count = = 0?) -Osspinlocklock (&table->slock); to     if(seen_weak_refs) { +Arr_clear_deallocating (&table->weak_table, obj);/** * * * **/ -     } theTable->refcnts.erase (Disguise (obj));/** * * * **/ *Osspinlockunlock (&table->slock); $}

In the Objc_destructinstance code above, the Object_cxxdestruct method is released first, which moves up the object's instance variable

Then remove the associated object

The third step clears the weak pointer

As you can see, clearing an instance variable of an object is uniformly cleaned up from the bottom up.

How do you ensure that this object is thread-safe when Dealloc receives a message while cleaning up the weak pointer?

Answer below:

When you get a weak pointer, you execute the following method, which has a spinlock, which is thread-safe when it cleans weak pointers at the same time.

That is, the result of this weak pointer is either empty or not empty, as long as it is not empty, it means that the memory area pointed to by the pointer is not released, and the instance variables inside the object may be cleaned out.

This time the message is sent to this pointer, does not bring crash, but the logic may be abnormal, this situation theoretically exists.

ID objc_loadweakretained (id *location) {    ID result;    Sidetable *table;    spinlock_t *lock; Retry:    result = *location;    if (!result) return nil;    Table = Sidetable::tableforpointer (result);    Lock = &table->slock;    Spinlock_lock (lock);    if (*location! = result) {        spinlock_unlock (lock);        Goto retry;    }    result = Weak_read_no_lock (&table->weak_table, location);    Spinlock_unlock (lock);    return result;}

  

4. References

http://stackoverflow.com/questions/30673101/is-it-safe-to-read-a-weak-pointer-while-its-being-deallocated

http://stackoverflow.com/questions/14854635/ how-can-the-objective-c-runtime-know-whether-a-weakly-referenced-object-is-still/14854977#14854977

http://blog.sunnyxx.com/2014/04/02/objc_dig_arc_dealloc/

  

Weak reference variable is thread safe

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.