一些学习过程中的难点解决
lock锁看了一片文章,写的很牛车:http://www.jb51.cc/article/p-dlsctegq-zv.html
例子
lock锁,我是用于两个线程同时执行一段代码或者一个方法,比如同时刷新auth认证,例如:
class ViewController: UIViewController {
let lock = NSLock()
var person = Person(name: "Leo",age: 23)
override func viewDidLoad() {
super.viewDidLoad()
let queue1 = dispatch_queue_create("com.test.queue1",DISPATCH_QUEUE_SERIAL)
let queue2 = dispatch_queue_create("com.test.queue1",DISPATCH_QUEUE_SERIAL)
dispatch_async(queue1) { () -> Void in
self.lock.lock()
self.person.update("queue1",delay: 2,age: 1)
self.lock.unlock()
}
dispatch_async(queue2) { () -> Void in
self.lock.lock()
self.person.update("queue2",delay: 1,age: 2)
self.lock.unlock()
}
self.performSelector("logPerson",withObject: nil,afterDelay: 4)
// Do any additional setup after loading the view,typically from a nib.
}
func logPerson(){
NSLog("%@ %d",person.name,person.age)
}
}
这样就会当执行 self.person.update(“queue2”,delay: 1,age: 2)时候锁定,执行完后释放锁,然后下一个线程才会重新调用update,这样数据不会错乱
我的代码是这样的:
case .Failure(let error):
if response.response?.statusCode == 401{//刷新token
dispatch_async(queue3) { () -> Void in
lock?.lock()//这里添加互斥锁,防止一起刷新token,这样就会分开之行token方法cjq
RefreshToken({ (AnyObject) in
lock?.unlock()
var hs = headers
hs!["Authorization"] = NSUserDefaults.standardUserDefaults().stringForKey("access_token")
}
},logout: { (NSError) in
logout?()
lock?.unlock()
})
}
}else{
failure?(error)
}
}
RefreshToken(success:((AnyObject?) -> Void)?,logout:((NSError?) -> Void))是闭包函数