调试期间,发现:
func newMessageSent(sentMessage: Message) { let conversationItemIdx:Int = SingletonConversationTVC().getConversationIndexFromId(sentMessage.receiverId) let conversationItem = self.conversationItemList[conversationItemIdx] let msgTVC = getMsgTVCFromItem(conversationItem.contactItem) // if self.notDuplicatedMessage(sentMessage, msgTVC: conversationItem.msgTVC) { if self.notDuplicatedMessage(sentMessage, msgTVC: msgTVC) { // self.updateConversationCell(sentMessage, conversationItem: conversationItem) conversationItem.updateContentFromMessage(sentMessage) self.updateConversationCell(conversationItem) // self.insertMessageAndScroll(sentMessage, msgTVC: conversationItem.msgTVC) self.insertMessageAndScroll(sentMessage, msgTVC: msgTVC) } } |
被两个线程,先后调用:
现象需要:
确保这个函数newMessageSent:
同一时刻只有一个访问
-》互斥性的访问
搜:
swift 互斥访问
Swift线程安全详解-概念,三种锁,死锁,Atomic,synchronized – Wenchen的专栏 – 博客频道 – CSDN.NET
iOS开发-多线程开发之线程安全篇 – GarveyCalvin – 博客园
swift function add lock
swift mutex
Simple synchronization functions for Swift, wrapping the Cocoa NSLocking classes
mikeash.com: Friday Q&A 2015-02-06: Locks, Thread Safety, and Swift
后来去改为:
var sentLock:NSLock self.sentLock = NSLock() func newMessageSent(sentMessage: Message) { self.sentLock.lock() let conversationItemIdx:Int = SingletonConversationTVC().getConversationIndexFromId(sentMessage.receiverId) let conversationItem = self.conversationItemList[conversationItemIdx] let msgTVC = getMsgTVCFromItem(conversationItem.contactItem) // if self.notDuplicatedMessage(sentMessage, msgTVC: conversationItem.msgTVC) { if self.notDuplicatedMessage(sentMessage, msgTVC: msgTVC) { // self.updateConversationCell(sentMessage, conversationItem: conversationItem) conversationItem.updateContentFromMessage(sentMessage) self.updateConversationCell(conversationItem) // self.insertMessageAndScroll(sentMessage, msgTVC: conversationItem.msgTVC) self.insertMessageAndScroll(sentMessage, msgTVC: msgTVC) } self.sentLock.unlock() } |
即可解决问题:
实现同一时刻只有一个线程访问此函数。
转载请注明:在路上 » [已解决]swift中如何确保函数的互斥访问