Friday, January 08, 2010

Parallel.For

Just thinking out loud:

function TfrmParallelForDemo.ParaScan(rootNode: TNode; value: integer): TNode;
var
nodeResult: TNode;
nodeQueue : TOmniBlockingCollection;
begin
nodeResult := nil;
nodeQueue := TOmniBlockingCollection.Create;
try
nodeQueue.Add(rootNode);
Parallel.ForEach(nodeQueue.GetEnumerator).Timeout(10*1000).Execute(
procedure (const elem: TOmniValue)
var
node : TNode;
iNode: integer;
begin
node := TNode(elem.AsPointer);
if node.Value = value then begin
nodeResult := node;
nodeQueue.CompleteAdding;
end
else for iNode := 0 to node.NumChild - 1 do
nodeQueue.TryAdd(node.Child[iNode]);
end);
finally FreeAndNil(nodeQueue); end;
Result := nodeResult;
end; { TfrmParallelForDemo.ParaScan }

I can make it compile (just did) and I think I can make it work.

Useful? Simple enough? What do you think?

6 comments:

  1. Very nice! (Though personally, seeing "then begin" together on the same line drives me up the wall. Makes it hard to line up begin/end pairs visually.)

    ReplyDelete
  2. I'm used to it :) My main preference when formatting code is to get as much as possible in the limited vertical space of the IDE editor while still preserving readability.

    ReplyDelete
  3. Useful for sure. Nowadays almost all decent machines how more that one core / processor. And a lot of loops could be faster if their code is paralel in nature. Funny, I was just thinking about exact same think two weeks ago. But since I didn't have any time to go further I stayed at that.

    ReplyDelete
  4. @gabr RE vertical space : Just a thought, but have you ever considered tilting your monitor to portrait mode? I use a 23" TFT in portrait mode - it works wonders for the vertical space! I have 110 lines of code on screen (when using a 9 point font like Consolas)! And the reduced horizontal space I can live with - there's enough space to fit 150+ characters.

    ReplyDelete
  5. @Patrick: Actually, I did try to work some time in vertical orientation but that suited me even less. As for the 9pt Consolas - you have a great eyesight! I'm working in Consolas 11.

    Maybe it's more "every line counts". 'Begin' is just a filler, most of the time. One line marking the start of the new block (if, while ...) should suffice. But that's just me and I'm not forcing others to use my coding style.

    ReplyDelete
  6. Anonymous14:00

    Thanks for your time :)

    ReplyDelete