IEnumerator and Foreach

I wanted to write a simple post about List enumeration and suddenly realise that here we as developers, are about to enter a pradigm shift. No longer is the default to develop for a single processor, threading will not be something that clever programs use. Almost everything is going to require scaling and queuing.  Why? Well here comes Core Duo. Two processors on a single piece of silicon. In fact I even read that servers are going to be offered with four Core Quad Chips. Welcome to the “many core” era.

I almost always use foreach for all list processing. Of course as we move into a many core world the standard concept of foreach just wont cut it anymore. Consider the following.

foreach (Data x in List<Data> list)
{
    Action.Do(x);
}

That just doesn’t take advantage of this extra power. It keeps all the processing on a single thread on a single Core of a single CPU. Looking for bottlenecks, start right there. Of course the reason we use this is because of its simplicity. Everyone can read this. It makes sense.

However there is an answer, and as usual it isn’t anything new. In fact it is the GoF Visitor pattern, and it’s already it the code above (sorry must stop cheating).

By defining the operation that we want to perform outside of the loop, in this case Action.Do(x); then we allow ourselves the opportunity to change the loop.

foreach (Data x in List<Data> list)
{
    Action.BeginDo(x);
}

Which only leaves us with one problem? How do we know when they are all finished?

Update:
I think just missed my own point here. Why? Well this is exactly the same thing that Eric Sink wrote about http://software.ericsink.com/entries/multicore_map.html in response to Joels post http://www.joelonsoftware.com/items/2006/08/01.html.

Advertisement