FileHandle.write 线程安全吗? [英] Is FileHandle.write thread safe?

查看:98
本文介绍了FileHandle.write 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试我的应用程序中难以捉摸的崩溃.在平稳运行几分钟后,应用程序将停止并显示 来自调试器的消息:由于内存问题而终止.没有堆栈跟踪.

I'm trying to debug an elusive crash in my app. After running uneventfully for many minutes, the app will halt with Message from debugger: terminated due to memory issue. There is no stack trace.

我已经确定崩溃与将字节复制到 UInt8 数组的一段代码有关.相同的数组可能会在紧接之前或之后写入文件系统.我从悲惨的经历中知道,您无法从不同线程的同一个数组中读取和写入数据.它导致崩溃,就像我正在经历的那样.但我在实施过程中一直非常小心.将字节写入数组的代码和从中读取字节的代码都运行在同一个串行 DispatchQueue 上.

I've determined the crash is linked to a section of code that copies bytes into a UInt8 array. That same array may be written to the file system immediately before or after. I know from sad experience that you can't read and write data to and from the same array from different threads. It leads to a crash very much like the one I'm experiencing. But I've been very careful in my implementation. The code that writes bytes to the array and the code that reads bytes from it all run on the same serial DispatchQueue.

但也许还有另一个话题?在 FileHandle.write 返回之前写入是否真的完成,或者是否有一些后台处理?

But maybe there's another thread? Does a write really complete before FileHandle.write returns, or is there some background processing?

func bug() {
    let bufferSize = ...
    var fileHandle:FileHandle = ...
    var fileIndex:UInt64 = ...

    var bytes = [UInt8](repeating:0, count:bufferSize)

    fileHandle.seek(toFileOffset: fileIndex)
    fileHandle.write(Data(bytes))
    for pos in 0..<bufferSize {
        bytes[pos] = ...        // Can my app crash here?
    }
}

推荐答案

FileHandle.write 不应创建另一个线程.我认为来自调试器的消息:由于内存问题而终止"错误的最可能解释是您的应用程序由于某种原因内存不足.可能有些东西没有正确释放.

FileHandle.write shouldn't create another thread. I think the most likely explanation of the "Message from debugger: terminated due to memory issue" error is that your app is running out of memory due to some reason. Probably something is not deallocating correctly.

您是否在循环中分配多个 UInt8 字节数组?

Are you allocating multiple UInt8 byte arrays in a loop?

这篇关于FileHandle.write 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆