This is my first one but certainly not the last one post about the concurrent programming in C#.
Free lunch is
over
is an excellent text which shows why concurrent programming matters. If you ever read anything about it, you
have probably noticed that
people talk about it as something hard and complicated. Is it really so hard
and
complicated? Well, in my opinion it depends. It depends about how much
concurrent your program need to be,
what kind of knowledge do you have about
this programming model, which libraries are you using for threading etc.
I
have some knowledge about this topic, but it's very far from being profound.
Because of that I'm happy that
there are some smart people in
Parallel
Computing Developer Center who made an excellent extension
for .NET -
ParallelFX.
There is a lot in it and there's a lot interesting topics to write about,
but because this is my first post, I will start
with something simple and
still very powerful. I will write only about Do method. According
to documentation,
it's a method with following declaration:
public static void Do(
params Action[] actions
)
This method "executes each of the provided actions inside a discrete,
asynchronous task". It doesn't
finishes until each
of provided actions has completed. That means, it will finish when the slowest
action finishes. Imagine
that you have two long running methods called
foo and bar. If you call them in sequential manner you will
need to
wait until foo finishes its execution, then you will run
bar method and wait until it finishes its execution. If you run
them
in parallel you will only need to wait as much as the longest of this two is
executing. Let's see an example.
class Program
{
private static double x = 1000000000;
private static void foo()
{ for (double i = 0; i < x; i++) ;}
private static void bar()
{ for (double i = 0; i < x; i++) ;}
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
foo();
bar();
watch.Stop();
Console.WriteLine("Not parallel: " +
(watch.ElapsedMilliseconds / 1000.0).ToString() +
"s");
watch.Reset();
watch.Start();
Parallel.Do(() => foo(), () => bar());
watch.Stop();
Console.WriteLine("Parallel: " +
(watch.ElapsedMilliseconds / 1000.0).ToString() +
"s");
}
}
The time which you get running the above program will depend about your
computer CPU. On my computer
(Core Duo, 2.33GHz) I get:
Not parallel: 8,769s
Parallel: 4,595s
So, with a help of just one line of code we have a multithreaded
program!
That's all for the first time. It was just a little introduction. When I
learn more about ParallelFX I will write again.