Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment a count value outside parallel.foreach scope

How can I increment an integer value outside the scope of a parallel.foreach loop? What's is the lightest way to synchronize access to objects outside parallel loops?

var count = 0; Parallel.ForEach(collection, item => {   action(item);   // increment count?? } 
like image 983
Cetin Sert Avatar asked Mar 06 '10 23:03

Cetin Sert


People also ask

Which is faster parallel ForEach or ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.

What is difference between ForEach and parallel ForEach in mule 4?

For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration.

Is parallel ForEach blocking?

No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.

Does ForEach work in parallel?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.


2 Answers

I like to beat dead horses! :)

The "lightest" way to increment the count from multiple threads is:

Interlocked.Increment(ref count); 

But as others have pointed out: if you're doing it inside Parallel.ForEach then you're probably doing something wrong.

I'm suspecting that for some reason you're using ForEach but you need an index to the item you're processing (it will never work with Parallel.ForEach). Am I close? Why do you need the count? What sort of VooDoo magic are you trying to do?

UPDATE:

You seem to be safe with the ConcurrentDictionary if your key is the URI and the value is TAnswer. I don't see a problem as long as you don't try to use the count to reference elements in your collection.

Finally...

If you need a counter, then use the Parallel.For loop... it safely increments the counter for you.

like image 82
Kiril Avatar answered Sep 22 '22 09:09

Kiril


Use Interlocked.Increment method in this way.

int count = 0; Parallel.ForEach(users, (u) => {     var currentCount = Interlocked.Increment(ref count);     Log(String.Format("Step {0} of {1}", currentCount, users.Count)); }); 
like image 37
Muhammad Ali Avatar answered Sep 20 '22 09:09

Muhammad Ali