最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]swift中如何确保函数的互斥访问

Swift crifan 1099浏览 0评论

调试期间,发现:

    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

Synchronization

swift mutex

Simple synchronization functions for Swift, wrapping the Cocoa NSLocking classes

Synchronization and Swift

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中如何确保函数的互斥访问

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
74 queries in 0.098 seconds, using 18.93MB memory