Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Race Condition in Async/Await Code

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?

like image 491
Tom K. Avatar asked Mar 03 '15 19:03

Tom K.


1 Answers

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.

like image 155
Stephen Cleary Avatar answered Oct 12 '22 20:10

Stephen Cleary