Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 迅捷的弦罕见的碰撞_Swift_Thread Safety_Automatic Ref Counting - Fatal编程技术网

Swift 迅捷的弦罕见的碰撞

Swift 迅捷的弦罕见的碰撞,swift,thread-safety,automatic-ref-counting,Swift,Thread Safety,Automatic Ref Counting,在我的应用程序中,我有一个记录器,可以将错误和状态消息写入字符串。它不是写在文件中的,只是在没有附加调试会话的情况下,当bug发生时,可以方便地查看一些东西 addLog()方法大约每3秒调用0-10次,非常简单: 每次调用都会将新添加的内容与发生的第二次添加一起添加到字符串的开头 为了防止字符串在大小上爆炸,如果它超过2kb,它将连续剪切“最旧”的100个日志字符,直到它再次小于2kb 代码如下所示: var logString = "" func addLog(s

在我的应用程序中,我有一个记录器,可以将错误和状态消息写入字符串。它不是写在文件中的,只是在没有附加调试会话的情况下,当bug发生时,可以方便地查看一些东西

addLog()方法大约每3秒调用0-10次,非常简单:

  • 每次调用都会将新添加的内容与发生的第二次添加一起添加到字符串的开头
  • 为了防止字符串在大小上爆炸,如果它超过2kb,它将连续剪切“最旧”的100个日志字符,直到它再次小于2kb
代码如下所示:

var logString = ""

func addLog(s : String){
    let date = Date()
    
    logString =  "\(date.second)\(s).\n\(logString)"
    
    while(logString.count>2000){
        logString=String(logString.dropLast(100))
    }
}
直到今天我收到一份事故日志,我才发现它有任何问题:

Thread 5 name:
Thread 5 Crashed:
0   libsystem_kernel.dylib          0x00000001c00f5414 __pthread_kill + 8
1   libsystem_pthread.dylib         0x00000001ddc50b50 pthread_kill + 272 (pthread.c:1392)
2   libsystem_c.dylib               0x000000019b5d3b74 abort + 104 (abort.c:110)
3   libsystem_malloc.dylib          0x00000001a1faf49c malloc_vreport + 560 (malloc_printf.c:183)
4   libsystem_malloc.dylib          0x00000001a1faf740 malloc_zone_error + 104 (malloc_printf.c:219)
5   libsystem_malloc.dylib          0x00000001a1f99ed8 free_small_botch + 40 (magazine_small.c:2215)
6   libswiftCore.dylib              0x00000001961103d8 _swift_release_dealloc + 40 (HeapObject.cpp:648)
7   APPNAME                         0x00000001046b56a0 AppDelegate.addLog(s:) + 960 (AppDelegate.swift:0)
日志本身的奇怪之处在于,
addLog()
函数不在我的AppDelegate的第0行,但在崩溃报告中出现错误的行可能是正常的


对于这个问题,我能想到的唯一可能的解释是,我的函数中存在线程安全问题,或者我遗漏了一些关于swift中垃圾收集的内容。很可能函数是同时从不同线程调用的,这可能是一个问题吗?还是我必须再次进入objective-c times
retain
等来解决这个问题?我能从这个崩溃日志中得到什么?

您必须处理串行队列中的所有更改。简单的修改:

private let queue = DispatchQueue(label: "addlog.queue")
private var logString = ""

func addLog(s : String) {
    queue.async { [weak self] in
        guard let self = self else { return }

        let date = Date()
        self.logString = String("\(date.second)\(s).\n\(self.logString)".prefix(2000))
    }
}

在您的情况下,您可以从不同的线程读取和写入“logString”参数,使用serial DispatchQueue处理带有参数make available to read and write parameter的所有操作一刻都无法读取和写入参数

线程安全性肯定需要解决。您在线程5上(用于崩溃),我想你没有料到。因此,
logString
存在线程安全问题。非常感谢!我不确定字符串是否也需要这样做,您的解决方案非常完美,谢谢!