swift 4.2 官方文档学习笔记(十七)- Memory Safety

Sellen Wei
1 min readDec 24, 2018

--

这一章是讲memory相关的,看完后应该能回答这几个问题:

  1. 什么情况下对于memory的访问会产生conflict?
  2. 什么是instantaneous?
  3. 什么是long-term accesses?

大部分情况下,如果出现内存访问冲突,会出现compile error或者run-time error,而这一章所讲的大部分冲突在平时工作中很少会有人这么写,我只把错误的code贴在这里做个记录,错误原因都显而易见,因此不予解释

最后一个例子中,如果不使用global 变量PlayerInformation,而使用局部变量:

就不会缠成冲突。

满足以下条件,则不会产生冲突:

You’re accessing only stored properties of an instance, not computed properties or class properties.

The structure is the value of a local variable, not a global variable.

The structure is either not captured by any closures, or it’s captured only by nonescaping closures.

最后,回答一下开始的几个问题:

什么情况下对于memory的访问会产生conflict?

A conflicting access to memory can occur when different parts of your code are trying to access the same location in memory at the same time.

什么是instantaneous?

An access is instantaneous if it’s not possible for other code to run after that access starts but before it ends. By their nature, two instantaneous accesses can’t happen at the same time. Most memory access is instantaneous.

什么是long-term accesses?

There are several ways to access memory, called long-term accesses, that span the execution of other code. The difference between instantaneous access and long-term access is that it’s possible for other code to run after a long-term access starts but before it ends, which is called overlap. A long-term access can overlap with other long-term accesses and instantaneous accesses.

--

--