线程安全回调函数

发布于 2024-10-07 02:46:56 字数 153 浏览 0 评论 0原文

如何使回调函数线程安全。这个函数会被不同的线程调用来更新UI。该回调函数将有一个 HWND 参数,该参数将由调用者填充。该函数将使用此 HWND 参数来更新 GUI。不同的调用HWND会有所不同。

请告诉我如何使这个回调线程安全。

问候。

约翰

How can i make a callback function thread safe. This function will be called by different threads to update UI. This callback function will have an HWND parameter which will be filled by the caller. The function will use this HWND parameter to update GUI. HWND will be different for different calls.

Please tell me how can i make this callback thread safe.

Regards.

John

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

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

发布评论

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

评论(1

£噩梦荏苒 2024-10-14 02:46:56

请告诉我如何确保此回调线程安全。

如果回调函数不需要任何状态,则它已经是线程安全的,除非 GUI 函数本身不是线程安全的(请参阅此答案的第二部分)。

如果需要状态,请在该状态中包含互斥锁,并在任何读/写访问期间锁定互斥锁。

还有更复杂的锁范例(例如多读取器/单写入器锁),但 GUI 可能不需要它。


GUI 的另一个问题(对于 Java Swing 是这样;我不记得对于 win32 是否如此)是 GUI 操作通常应该在一个特定的线程中执行。在 win32 中,这就是发布和发送消息(由一个线程处理)的原因。

如果你想使用这种方法,任何时候你想执行 GUI 操作,你应该检查你是否在 GUI 线程中(不记得在 win32 中如何做到这一点),或者执行 PostMessage() 调用来启动特定的 GUI 操作。

Please tell me how can i make this callback thread safe.

If there's no state required by the callback function, it's already threadsafe, unless the GUI functions themselves are not threadsafe (see the 2nd half of this answer).

If there is state required, include a mutex in that state, and lock the mutex during any read/write accesses.

There are more complex lock paradigms (e.g. multiple-reader/single-writer locks) but you probably won't need that for a GUI.


The other issue for GUIs (true for Java Swing; I can't remember whether this is true for win32 or not) is that GUI operations should usually be performed in one particular thread. In win32, that's the reason for posting and sending messages (which are processed by one thread).

If you wanted to use this approach, anytime you want to perform a GUI operation, you should check whether you are in the GUI thread (can't remember how to do that in win32), or perform a PostMessage() call to kick off particular GUI operations.

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