如何使用多线程提高性能?

发布于 2025-01-01 02:27:12 字数 355 浏览 4 评论 0原文

我有一个程序,它从其他应用程序接收字符串消息并使用 VCL 解析它们。 消息的发送方式如下:

AtomId := GlobalAddAtom(PChar(s));
SendMessage(MyProgramHandle, WM_MSG, 0, AtomID);
GlobalDeleteAtom(AtomID);

我的程序接收此消息,解析它一段时间,然后将控制权返回给应用程序。 解析一条消息需要时间,因此其他应用程序的性能会变差。

一种可能的解决方案是在其他线程中创建具有相同标题和相同类的表单,并重命名主表单的类。 但据我所知,不建议在线程中创建表单。

那么,有哪些可能的方法可以提高性能呢?

I've got a program which receives string messages from other applications and parses them using VCL.
Messages are sent as follows:

AtomId := GlobalAddAtom(PChar(s));
SendMessage(MyProgramHandle, WM_MSG, 0, AtomID);
GlobalDeleteAtom(AtomID);

My program receives this message, parses it for some time, and then returns control to an application.
It takes time to parse one message so perfomance of other applications worsens.

One possible solution is to create form with the same caption and the same class in other thread, and rename class of main form.
But as far as I know it isn't recommended to create forms in threads.

So, what are possible ways to improve perfomance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情栀口红 2025-01-08 02:27:12

典型的方法是创建一个工作线程(或工作线程池)。主线程将继续接收消息,但不会解析它们,而是将它们添加到队列(例如链表)中。

工作线程获取队列中的第一个元素并处理它。完成后,它返回队列以获取下一个元素。

由于队列是多个线程之间的共享资源,因此您必须控制对其的访问。互斥锁将确保在任何给定时间只有一个线程可以访问队列。

祝你好运。

The typical approach would be to create a worker thread (or a pool of worker threads). The main thread will continue to receive the messages, but instead of parsing them it will just add them to a queue (a linked list, for example).

The worker thread takes the first element in the queue and processes it. When done it goes back to the queue to get the next element.

Since the queue is a shared resource between multiple threads you have to control access to it. A mutex will ensure that only one thread gets access to the queue at any given time.

Good luck.

风和你 2025-01-08 02:27:12

那么问题是消息的接收和VCL操作都是在同一个线程(VCL主线程)中完成的吗?因此,接收和处理是序列化的,因此当您的应用程序忙于填充网格时,发送者会被阻止?那么我可以理解您要求一种将接收移动到不同窗口消息循环的方法。

因此,我将创建一个窗口(不是 VCL 表单),仅用于接收消息并使用其消息循环将消息添加到队列中。所以你只需要找到这个(非VCL)窗口并向其句柄发送消息即可。在 VCL 线程中,计时器可以获取接下来的“n”条消息并将它们添加到网格中。

So the problem is that both the receiving of the messages and the VCL operations are done in the same thread (the main VCL thread)? And so the receiving and processing are serialized and as result the senders are blocked while your app is busy filling the grid? Then I can understand that you ask for a way to move the receiving to a different window message loop.

So I would create a window (not a VCL form) only for the purpose to receive messages and use its message loop to add message to a queue. So you only need to find this (non-VCL) window and SendMessage to its handle. In the VCL thread, a Timer could fetch the next "n" messages and add them to the grid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文