Multi-threaded _ Mutual exclusion lock solve ticket problem

Source: Internet
Author: User
Tags mutex ticket

In this website introduces the security hidden trouble of multithreading http://blog.csdn.net/u012745229/article/details/50939252
Questions about buying Tickets

To use a mutual exclusion lock:

@interface Viewcontroller ()

//Total votes

@property (nonatomic,assign) int tickets;

@end
-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *) event
{
    //20 Tickets
    remaining self.tickets=20;

    Add child thread
    nsthread *threada=[[nsthread alloc] initwithtarget:self selector: @selector (saletickes) Object:nil];
    threada.name=@ "Ticket clerk a";
    [Threada start];

    Nsthread *threadb=[[nsthread alloc] initwithtarget:self selector: @selector (saletickes) Object:nil];
    threadb.name=@ "ticket clerk B";
    [threadb start];
}
/*
 lock, Mutex lock
 , lock code as little as possible
 lock the code within the range, agree to four pieces run only one thread to execute
 the mutex parameters, any inherited NSObject * object can be
 guaranteed this lock, so the thread can access to, And all threads are accessing the same lock
 *
/-(void) Saletickes
{
    while (YES)
    {

        ///simulate delay, buy a ticket for 1 seconds of rest
        [nsthread SLEEPFORTIMEINTERVAL:1.0];

        Apple does not recommend us to use because the lock performance will be
        poor
         /* pros and cons
         a bit can solve the problem of resource sharing problems of data access
         ; it consumes a lot of CPU resources.
         *

        /@synchronized ( Self)//in which object creates a lock <----
        {
            //determines if there is still a ticket if
            (self.tickets>0)
            {
                //2. If you have a ticket, buy one
                . self.tickets--;
                NSLog (@ "Number of votes left--%d--%@", Self.tickets,[nsthread CurrentThread]);
            }
            else
            {
                NSLog (@ "no ticket");
                Break;}}}}

Why are mutexes used infrequently in development?
When you buy a ticket, the number of votes is accessed through the Server database query.
Unless you add the mutex to the server.
Is that you lock the mutex on your mobile app. No mutex on Android phone or website access

So Apple suggests we use "spin lock"

@interface Viewcontroller ()

//Total votes

@property (nonatomic,assign) int tickets;


@property (Atomic,strong) nsobject *obj;

Nonatomic Non-atomic attribute
//atomic Atomic attribute default attribute
//Atomic attribute is designed for multithreading, atomic attributes implement single (thread) write multiple (thread) read
//Because write security levels are richer and read less demanding, Can be more than a few times to ensure the correctness of
@end
@synthesize obj=_obj;

-(NSObject *) obj
{
    return _obj;
}

/* The
 concept of thread safety
 is to ensure the accuracy of resource information when multiple threads are executing simultaneously
 "UI thread---main thread"
 Uikit most of the classes are not "thread safe"
 How to solve this thread unsafe problem?
 Apple conventions, so the program's update UI is all on the main thread so the UI is updated in the main thread, which does not change the

 benefits of a resource in the main thread update UI at the same time
 1. Only the main thread updates the UI, one does not appear multithreaded and changes the same UI control
 2. The main thread of the highest priority, it means that the UI update priority is high, will make the user feel and fluent
 * *

//atomic case, as long as the set method is written, getter also rewrite
-(void) Setobj: (NSObject * obj {//

    Atomic wake-up internal use of spin lock//spin
    lock and mutex
    //common denominator; You can shorten a piece of code at the same time, only the thread can execute the lock code
    //difference: Mutex, when locked, Other threads go to sleep, wait for the condition to meet in the wake
    //Spin Lock: When locked, other threads do a dead loop, always waiting for this condition to meet, once the fulfillment inside executes, less wake
    @synchronized (self)
    {
        _ obj=obj;
    }
}

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.