Can anyone make heads or tails of this? Am I missing something?

Can anyone make heads or tails of this?  Am I missing something?

procedure TMySocketTasks.Execute;
begin
  CoInitialize(nil);
  while not Terminated do
  begin
    try
      while (TaskStatus <> stsJobInQueue) do
      begin
        sleep(1);
        if Terminated then exit;
      end;
      TaskExecute;
    except
      TaskErrMsg  := 'Unknown Error On Socket';
      TaskErrCode := 1;
    end;
  end;
  CoUnInitialize;
end;

Comments

  1. I want the same drugs that guys on.

    ReplyDelete
  2. Hey, thanks I know it's crap. I am I just want to know what he's trying to do! :-)

    ReplyDelete
  3. Nick Hodges Aw, come on now, you don't mean it! ;)

    ReplyDelete
  4. I had to maintain code once that wrapped the entire function in a try..catch.  Tried to execute something 3 times and then exit the function as if nothing had happened. 

    fun times

    ReplyDelete
  5. Despite some obvious missing things like a finally for the CoUninitialize and an Exit inside the except (otherwise he might just stumble into the same error again), he is waiting for a specific state (stsJobInQueue) and then handle that job via TaskExecute. Do that again until the user quits the program. I can't see more from this code part.

    ReplyDelete
  6. In that particular case the try finally on CoInitialize would be purely cosmetic, as whatever could trigger an exception there means the process is already ripe with dangling pointers and memory corruptions.

    Other than that its a waiting loop with polling on a state, placed in a thread so as not to block the main thread I would guess, better performing alternatives would be to use IOCP (best solution) or an event/wait, though in both cases, you'll need extra scaffolding to handle the Terminated checks (because the Delphi RTL designers didn't bother to have anything beyond a Boolean for it).

    ReplyDelete
  7. You can find IOCP in mORMot & DWS web server.

    For worker threads, the IOCP API is quite straightforward though:
    - create a queue with CreateIoCompletionPort
    - push tasks to the queue with PostQueuedCompletionStatus
    - and in your worker threads pop tasks with GetQueuedCompletionStatus

    And since it's kernel-based, it scales much better than custom event signaling and without the thread safety and concurrency issues using your own (user-mode) queue class would have.

    The only thing that is complicated is that the IOCP functions in the WinAPI have "creative" names, and that you've got to pass your tasks through the IOCP Data structure (ie. with a pointer).

    ReplyDelete

Post a Comment