编写多线程代码时,总是存在出现竞争条件的风险。当一个操作的输出取决于不受其控制的另一个过程的时序时,即出现竞争条件。
竞争条件并不总是错误,但它是不确定行为的根源。当竞争条件确实会导致错误时,可能很难找到问题的根源,因为这种情况取决于时序,所以只有在极少数情况下可以复现问题。对此情况进行调试可能会导致问题消失,因为断点和日志记录可能会改变各个线程的时序。竞争条件是编写多线程代码时遭遇的最大挑战。
为了更容易编写多线程代码,Unity C# 作业系统可以检测所有潜在的竞争条件,并尽量避免可能导致的错误。
例如:如果 C# 作业系统将主线程中对代码数据的引用发送给一个作业,则系统无法验证主线程在读取数据的同时是否该作业正在写入数据。这种情况下便会产生竞争条件。
C# 作业系统解决这个问题的方法是向每个作业发送其需要操作的数据的副本,而不是对主线程中的数据进行引用。此副本可以隔离数据,从而消除竞争条件。
C# 作业系统复制数据的方式意味着作业只能访问 blittable 数据类型。在托管代码和本机代码之间传输时,这些类型不需要转换。
C# 作业系统可以使用 memcpy 复制 blittable 类型,并在 Unity 的托管部分和本机部分之间传输数据。在调度作业时,系统使用 memcpy
将数据放入本机内存,并在执行作业时让托管端访问该副本。有关更多信息,请参阅调度作业。
2018–06–15 页面已发布
在 2018.1 版中公开了 C# 作业系统 NewIn20181
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.