编写多线程代码时,总是存在出现竞争条件的风险。当一个操作的输出取决于不受其控制的另一个过程的时序时,即出现竞争条件。
A race condition is not always a bug, but it is a source of nondeterministic behavior. When a race condition does cause a bug, it can be hard to find the source of the problem because it depends on timing, so you can only recreate the issue on rare occasions. Debugging it can cause the problem to disappear, because breakpoints and logging can change the timing of individual threads. Race conditions produce the most significant challenge in writing multithreaded code.
为了更容易编写多线程代码,Unity C# 作业系统可以检测所有潜在的竞争条件,并尽量避免可能导致的错误。
For example: if the C# Job System sends a reference to data from your code in the control thread to a job, it cannot verify whether the control thread is reading the data at the same time the job is writing to it. This scenario creates a race condition.
The C# Job System solves this by sending each job a copy of the data it needs to operate on, rather than a reference to the data in the control thread. This copy isolates the data, which eliminates the race condition.
C# 作业系统复制数据的方式意味着作业只能访问 blittable 数据类型。在托管代码和本机代码之间传输时,这些类型不需要转换。
C# 作业系统可以使用 memcpy 复制 blittable 类型,并在 Unity 的托管部分和本机部分之间传输数据。在调度作业时,系统使用 memcpy
将数据放入本机内存,并在执行作业时让托管端访问该副本。有关更多信息,请参阅调度作业。
2018–06–15 页面已发布
在 2018.1 版中公开了 C# 作业系统 NewIn20181