Click here to Skip to main content
Click here to Skip to main content

PLinq and source IEnumerable thread safety

By , 3 Sep 2012
 

As I discovered that the source IEnumerable is called by PLINQ from multiple threads, it made me thinking: how can it possibly work? E.g. when someone writes code like this:

Enumerable.Range(1,1000).AsParallel()...

the Range iterator must keep its current state in some variable. If this state is accessed from multiple threads, how are race conditions avoided? Here are my findings in order:

1. Enumerable.Range() returns an IEnumerable<int>. This enumerable’s GetEnumerator() will return different enumerators for different threads. This appears to be a built-in feature of enumerables generated from yield return keyword. Reflector is my witness. Proof link.

Each enumerator, however, is not thread safe and does not have any locking code.

2. AsParallel() calls GetEnumerator() only once, and then uses it from multiple threads, so the above protection does not work.

3. Stephen Toub of Microsoft says, that as IEnumerable is inherently thread unsafe, PLINQ has locking built in.

4. As per Reflector it appears to be implemented in the PartitionedDataSoruce<T>.MoveNext() method.

So, relax folks. Your enumerator can and will be thread unsafe, PLINQ has its own locks to take care of that.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

About the Author

Ivan Krivyakov
Architect Sungard Consulting Services
United States United States
Member
Ivan is a hands-on software architect working for SunGard Consulting, in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.
 
Please visit my web site: www.ikriv.com.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 3 Sep 2012
Article Copyright 2012 by Ivan Krivyakov
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid