Swift's detailed------------nsthread thread sync lock

Source: Internet
Author: User
Tags ticket

Nsthread Thread Sync Lock

The above section uses Nsthread to realize the reading of the network picture, which NSThread simulates a ticket selling example. Use NSLock or NSCondition lock resources

var100//总票数    var0  //窗口1卖出票数    var0   //窗口2卖出票数    vartrue  //是否出售    varlock:NSLock?       var condition:NSCondition?

Here we first define some variables

Then click on the ticket to open a thread to imitate the window

 lock = NSLock()        condition = NSCondition()        //setTicketValue()        NSThreadself"run"nil)        thread1.name"thread-1"        thread1.start()        NSThreadself"run"nil)        thread2.name"thread-2"        thread2.start()
Func run () { while(IsSell) {lock?. Lock()if(total>0){Nsthread. Sleepfortimeinterval(0.2); total--if(Nsthread. CurrentThread(). Name=="Thread-1") {w1++}Else if(Nsthread. CurrentThread(). Name=="Thread-2") {w2++}Dispatch_async(Dispatch_get_main_queue ()) { Self. Setticketvalue()                }            }Else{Dispatch_async(Dispatch_get_main_queue ()) { Self. Totalticks. Text="The tickets are sold out."                     Self. IsSell=false}} lock?. Unlock()        }    }

This is probably a small example.
Source code: Source Code

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift's detailed------------nsthread thread sync lock

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.