Race Condition in Async/Await Code

两盒软妹~` 提交于 2019-12-18 21:49:30

问题


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;
}

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.

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.

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


回答1:


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

Also see the comments on: http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx

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.




回答2:


There are a number of things that could be going on here.

For one, what sort of executable are you running? When Await fires, it uses the current synchronization context, so your awaited code could be getting serialized to 1 a UI thread.

Also, since there is no memory barrier/volatility protection around the variable, your threads might be reading indiviually cached values (as mentioned by @Spo1ler in his post)

Also, the thread pool might be choosing to run both your requests on the same thread (it's within its rights to do so -- you're letting .net/windows decide when and how to allocate threads)

Bottom line though, you really should be protecting the access to the variable with synchronization or interlocked operations.



来源:https://stackoverflow.com/questions/28840059/race-condition-in-async-await-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!