德尔福多线程消息循环 [英] Delphi Multi-Threading Message Loop

查看:176
本文介绍了德尔福多线程消息循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有几个线程:
1)主线程
2)2个主线程(每个都有Message Loop,如下所示),由TFQM
3)n工作线程(简单循环,包含Sleep())

My application has several threads: 1) Main Thread 2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM 3) n Worker Threads (simple loop, containing Sleep())

我的问题是,当我关闭我的应用程序时,Worker Threads设置正确退出,当我发出WM_QUIT关闭它们时,主线程挂起(永远不会退出)。

My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM_QUIT to close them.

procedure ThreadProcFQM(P: Integer); stdcall;
var
  Msg: TMsg;
 _FQM: TFQM;
begin
  _FQM := Ptr(P);
  try
    _FQM.fHandle := AllocateHwnd(_FQM.WndProc);

    while GetMessage(Msg, 0, 0, 0) do
    begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;

  finally
    DeallocateHWnd(_FQM.fHandle);
    SetEvent(_FQM.hTerminated);
  end;
end;







procedure TFQM.Stop;
begin
  PostMessage(fHandle, WM_QUIT, 0, 0);

  WaitForSingleObject(hTerminated, INFINITE);
  if hThread <> INVALID_HANDLE_VALUE then
  begin
    CloseHandle(hThread);
    hThread := INVALID_HANDLE_VALUE;
  end;
end;


推荐答案

如果我可以指出你的代码中的几个问题。 ..

If I may point to few problems in your code ...

1)您没有检查AllocateHwnd的输出。是的,很可能永远不会失败,但仍然...

1) You're not checking output of AllocateHwnd. Yes, most probably it will never fail, but still ...

2)分配Hwnd belogs OUT的try..finally!如果失败,则不应该调用DeallocateHwnd。

2) AllocateHwnd belogs OUT of try..finally! If it fails, DeallocateHwnd should not be called.

3)AllocateHwnd不是线程安全的。如果您在同一时间从多个线程中调用它,则可以运行到poblems。 阅读更多。

3) AllocateHwnd is not threadsafe. If you call it from multiple threads at the same time, you can run into poblems. Read more.

正如Davy所说,使用MsgWaitForMultipleObjects而不是创建隐藏的消息窗口。然后使用PostThreadMessage将消息发送到线程。

As Davy said, use MsgWaitForMultipleObjects instead of creating hidden message window. Then use PostThreadMessage to send messages to thread.

如果我可以在这里放置一个完全免费的产品的插件 - 请使用我的 OmniThreadLibrary 。比直接使用Windows消息传送更简单。

If I may put a plug for a totally free product here - use my OmniThreadLibrary instead. Much simpler than messing directly with Windows messaging.

这篇关于德尔福多线程消息循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆