异步/等待代码中的竞争条件 [英] Race Condition in Async/Await Code

查看:80
本文介绍了异步/等待代码中的竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

另请参阅以下评论: http://blogs.msdn.com/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.

这篇关于异步/等待代码中的竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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