从工作非 gui 线程向主窗口发送消息 [英] Sending message from working non-gui thread to the main window
问题描述
我使用的是 WinApi.
I'm using WinApi.
SendMessage/PostMessage 是一种与主窗口通信的线程安全的好方法吗?假设工作线程正在创建一个必须显示在屏幕上的位图.工作线程分配一个位图,发送一个带有指向该位图的指针的消息,并等待 GUI 线程处理它(例如使用 SendMessage).工作线程不与其他线程共享数据.
Is SendMessage/PostMessage a good, thread safe method of communicating with the main window? Suppose, the working thread is creating a bitmap, that must be displayed on the screen. The working thread allocates a bitmap, sends a message with a pointer to this bitmap and waits until GUI thread processes it (for example using SendMessage). The working thread shares no data with other threads.
这样的设计我遇到了麻烦吗?
Am I running into troubles with such design?
是否还有其他不引入线程同步、锁定等的可能性?
Are there any other possibilities that do not introduce thread synchronizing, locking etc. ?
推荐答案
这是一个不错的线程同步方法,应该没问题,只要你小心:
This is a decent method of thread synchronisation, and should be fine, so long as you're careful that:
- 要么主线程保留位图,而工作线程启动一个新的位图,反之亦然,这样在 SendMessage 返回后,只有一个线程可以访问位图.
- 稍后您不会不小心将 SendMessage 更改为 PostMessage,而忘记了它提供您的同步以及线程间通信.
这篇关于从工作非 gui 线程向主窗口发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!