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