cool hit counter Data Security under Multi-Threading in iOS_Intefrankly

Data Security under Multi-Threading in iOS


Problems with multi-threaded manipulation of shared resources
  • In a multi-threaded environment, a shared resource may be shared by multiple threads, i.e. multiple threads may operate on the same resource.
  • When multiple threads operate on the same resource, it is easy to cause data misalignment and data security problems, data may be lost, added, or misaligned.
  • Classic example : Train station ticket sales, commodity rush
  • Thread-safe: A thread is safe when the same resource is read or written to by multiple threads at the same time, and still gets the correct result.
How to solve

How to protect shared data during multi-threaded operations is actually a well-known thing, and here's a summary of how you've tried to handle it.

  • @synchronized
  • NSLock
  • dispatch_semaphore_signal
@synchronized

is to create a mutually exclusive lock that ensures that no other threads make changes to the self object at this time. This is an objective-c locking token that prevents self objects from being accessed by other threads at the same time, acting as a thread protection. Advantages and disadvantages of interlocking. Advantages: effective in preventing data security problems caused by multiple threads grabbing resources. Disadvantage: requires a lot of CPU resources.

dispatch_semaphore

dispatch_semaphore is a way for GCD to synchronize, and there are three functions associated with him, which are dispatch_semaphore_create,dispatch_semaphore_signal,dispatch_semaphore_wait。

(1) The dispatch_semaphore_create is declared as. dispatch_semaphore_t dispatch_semaphore_create(long value); The argument passed in is long and outputs a semaphore of type dispatch_semaphore_t with the value value. It is worth noting that the value of the argument passed in here must be greater than or equal to 0, otherwise dispatch_semaphore_create will return NULL.

(2) The dispatch_semaphore_signal is declared as dispatch_semaphore_signal(semaphore); This function adds 1 to the value of the semaphore passed in.

(3) The dispatch_semaphore_wait is declared as dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); This function decrements the value of the incoming semaphore by 1; this function works like this, if the value of the semaphore semaphore is greater than 0, the thread the function is in continues to execute the following statement and decrements the value of the semaphore by 1; if the value of the semaphore is 0, then the function blocks the current thread waiting for timeout

The following is an example of the use of the canonical case to purchase train tickets

@interface ViewController ()
{
    dispatch_semaphore_t semaphore;
}

@property (assign, nonatomic) NSInteger ticketNumber;
@property (strong, nonatomic) NSLock *lock;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.ticketNumber = 100;
    self.lock = [[NSLock alloc]init];
    semaphore = dispatch_semaphore_create(1);
    
    for (NSInteger i = 0; i < 10; i++) {
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sellTicketsWithNSLock) object:nil];
        [thread setName:[NSString stringWithFormat:@" ticket seller-%zd",i]];
        [thread start];
    }
}
@end
Using Synchronized
- (void)sellTicketsWithSynchronized
{
    while (true) {
        @synchronized(self){
            if (self.ticketNumber > 0) {
                self.ticketNumber --;
                NSThread *thread = [NSThread currentThread];
                NSLog(@"%@Sold a ticket., there remains%ld ticket",[thread name],self.ticketNumber);
            }else{
                 // Exit the current thread
                [NSThread exit];
            }
        }
    }
}
Using NSLock
- (void)sellTicketsWithNSLock
{
    while (true) {
        [self.lock lock];
        if (self.ticketNumber > 0) {
            self.ticketNumber --;
            NSThread *thread = [NSThread currentThread];
            NSLog(@"%@Sold a ticket., there remains%ld ticket",[thread name],self.ticketNumber);
        }else{
             // Exit the current thread
            [NSThread exit];
        }
          [self.lock unlock];  // Unlock
    }
}
Using Semaphore
- (void)sellTicketsWithSemaphore
{
    while (true) {
        // signal==0 Just block the current thread and waittimeout,>0 Just continue with the following statement The value of the semaphore is reduced by1
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        if (self.ticketNumber > 0) {
            self.ticketNumber --;
            NSThread *thread = [NSThread currentThread];
            NSLog(@"%@Sold a ticket., there remains%ld ticket",[thread name],self.ticketNumber);
        }else{
             // Exit the current thread
            [NSThread exit];
        }
         // Signal +1
        dispatch_semaphore_signal(semaphore);
    }
}

Demo address.https://github.com/destinyzhao/ThreadSafeDemo


Recommended>>
1、Get out of these six misconceptions before you really understand bitcoin
2、Baidu Security hosts BCTF Matchmaking Campus Live protects the good life with AI
3、Chinas first driverless crossseat monorail line officially opened to traffic
4、Flying cars are really coming Possible commercial use within 5 years
5、wwwtyc38com

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号