C# parallel programming with list - is reading thread-safe? -
i'm reading book parallel programming says it's not thread save add elements list without using lock result unpredictable. example if have add 800 000 elements list, final result have less 800 000 elements.
now wondering if thread save read elements list. example lets have list blacklistednumbers
list<int> blacklistednumbers = new list<int> {10, 50 ....... n}; //lets there 500 000 elements in list
and list numbers
containing 10 000 000 numbers, i'll use parallel.foreach complete task , want final
list containing numbers numbers
not in blacklistednumbers
list
list<int> finallist = new list<int>(); parallel.foreach(numbrs, num => { if (!blacklistednumbrs.contains(num)) { lock (finallist) { finallist.add(num); } } });
i know not efficient way done i'm trying illustrate problem.
so question is: thread save read result list blacklistednumbrs
, 100% accurate results?
from msdn:
a
list<t>
can support multiple readers concurrently, long collection not modified.
so if never modify list, should fine.
note using hashset<int>
rather more efficient - , hashset<t>
supports multiple readers1. can also use parallel linq make query sweeter , more efficient:
// if want duplicates in numbers still come duplicates in result hashset<int> blacklistedset = new hashset<int>(blacklistednumbers); list<int> finallist = numbers.asparallel() .where(x => !blacklistedset.contains(x)) .tolist(); // or if want set-based operation: list<int> finallist = numbers.asparallel() .except(blacklistedset) .tolist();
much nicer, , no locking required :)
1 noted in comments, don't have documentation up. reading set doesn't need modify shared state, @ least makes sense...
Comments
Post a Comment