异步/等待代码中的竞争条件

编程入门 行业动态 更新时间:2024-10-25 13:15:12
本文介绍了异步/等待代码中的竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只是想知道下面的代码中是否出现竞争条件:

I just wonder whether a race condition occurs in the code below:

int readingFiles; async Task<string> ReadFile (string file) { ++readingFiles; var text = await Stream.ReadFileAsync(file); --readingFiles; return text; }

如果ReadFile方法是由线程池线程执行的,则readFiles将由两个不同的线程访问,并且readFiles变量不受任何同步习语的保护.

If ReadFile method is executed by a thread pool thread, readingFiles will be accessed by two different threads and the readingFiles variable is not protected by any synchronization idioms.

这意味着对readFiles的第一次更新对于执行"--readingFiles"的其他线程不可见.但是,我从未见过在"--readingFiles"之后,readingFiles等于-1.我使用Thread.CurrentThread检查同一线程是否执行++和-操作.在大多数情况下,它不是同一线程,我仍然看不到readFiles为-1.

It means that the first update to readingFiles should not be visible to the other thread executing "--readingFiles". However, I've NEVER seen that readingFiles equals -1 after "--readingFiles". I check whether the same thread executes the ++ and -- operations by using Thread.CurrentThread. In most cases, it is not the same thread and I still do not see readingFiles as -1.

即使存在竞争条件,并且readFiles也不不稳定,为什么我看不到这种竞争条件的影响?

Even though there is a race condition and readingFiles is not volatile, why do not I see the effect of this race condition?

推荐答案

此处没有竞争条件. .NET运行时将插入适当的内存屏障.

There is no race condition here. The .NET runtime will insert the appropriate memory barriers.

另请参阅以下评论: blogs.msdn/b/pfxteam/archive/2012/04/12/async-await-faq.aspx

是的,TPL在任务排队时以及在任务执行的开始/结束时包括适当的障碍,以使值适当可见.

Yes, TPL includes the appropriate barriers when tasks are queued and at the beginning/end of task execution so that values are appropriately made visible.

更多推荐

异步/等待代码中的竞争条件

本文发布于:2023-10-23 19:49:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   竞争   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!