Summary of usage of @synchronized (self)

Source: Internet
Author: User

The role of @synchronized () is to create a mutex that ensures that no other thread modifies the self object at the same time, and that it acts as a thread protection and is generally used in common variables, such as singleton mode or static variables of an operation class.

Example One:// implementation of a single case Student.h # Import < foundation/foundation.h> @ Interface << Span style= "font-style:normal; Font-variant:normal; Font-weight:normal; Font-family:menlo ">nscopying, NSMutableCopying > @ Propertynonatomic, copy) NSString *name; //1, declare a class method in the H file to initialize the instance + (ID) sharestudent; @end STUDENT.M #import "Student.h" / /2 , in .m file first declare a static Modified object, this object is a null pointer at this time static Student *stu = nil; @implementation Student //3, Implementing A class method declared in. h + (ID) sharestudent{ // Avoid the drawbacks of multi-threaded operation (mutual exclusion lock) @synchronized(Self){
If(Stu==Nil) {
Stu= [[Student alloc ]init        }
        return stu    } }4AvoidAllocCreates a new object, so you want to overrideAllocwithzoneMethod
+(Instancetype) Allocwithzone: (struct_nszone*) zone{
If(Stu==Nil) {
Stu = [super Allocwithzone: zone];
}
return Stu; }5To avoid copying and creating new objects, we need to rewriteCopywithzoneAndMutablecopywithzoneMethod
-(ID) Copywithzone: (nszone *) zone{
return Stu; }-(ID) Mutablecopywithzone: (nszone *) zone{
return Stu; }@endExample Two:// implementation of the operation class

# import "NetworkManager.h"

Static NetworkManager *Network = nil;

@implementation NetworkManager

+ (NetworkManager *)getnetworkinstance{

@synchronized(self) {

if (nil = = Network) {

Network = [[NetworkManager alloc] init];

{

}

return network;

}

Summary of usage of @synchronized (self)

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.