【问题标题】:Alternative to postThreadMessage/peekmessage?postThreadMessage/peekmessage 的替代方案?
【发布时间】:2014-04-03 15:04:02
【问题描述】:

我的 C++ 应用程序中有一个(静态)线程,经常做一些事情。为了在线程和我的应用程序之间交换信息,我使用方法PostThreadMessage 和PeekMessage。

由于某种原因,我不能再使用这些方法,但不知道有什么好的替代方法。有人有建议吗?我只是想交换简单的参数。

【问题讨论】:

  • 这些方法似乎是特定于您的应用程序或特定于您的框架......在任何一种情况下,如果不了解您的应用程序的更多信息,就很难提供答案。你能加点scce吗?
  • 对不起,我忘了提到这两种方法都是 WinAPI 的一部分。它们很适合在线程中发送和接收信息。很简单。我正在寻找替代方案。
  • 你为什么要尝试使用其他东西? peek消息有什么问题?也许你可以改变它以满足你的需要。
  • 自己做这一切,您可以拥有一个包含消息容器的队列。您需要使用互斥锁来保护它,以确保您不会从两个同时线程中修改它。它需要包含在主线程和工作线程都可以访问的地方(例如,单例或提供给线程的引用)。这是一个简单的设置。寻找更复杂的东西……你可能想看看ACE library……但那是一个全新的世界。
  • 认为自己很幸运,您应该永远使用 PostThreadMessage() 将消息发布到创建窗口的应用程序。改用 PostMessage(),你需要知道窗口句柄。

标签: c++ multithreading winapi


【解决方案1】:

正如你在评论中所说,你没有理由不能“与主线程交换简单对象”。在线程之间共享类实例的常见模式是执行以下操作:-

使用可以被_beginthread 定位的static 函数和可以完成工作的实例函数声明您的类:

class CMyClass
{
    // ... other class declarations ...

private:
    static void __cdecl _ThreadInit(void *pParam);    // thread initial function
    void ThreadFunction();                            // thread instance function

    void StartThread();                               // function to spawn a thread

    // ... other class declarations ...
};

像这样定义函数:

void CMyClass::StartThread()
{
    // function to spawn a thread (pass a pointer to this instance)
    _beginthread(CMyClass::_ThreadInit, 0, this);
}

void __cdecl CMyClass:_ThreadInit(void *pParam)
{
    // thread initial function - delegate to instance
    CMyClass *pInstance = (CMyClass*)pParam;
    pInstance->ThreadFunction();
}

void CMyClass:ThreadFunction()
{
    // thread instance function is running on another
    // thread but has (hopefully synchronised) access
    // to all of the member variables of the CMyClass
    // that spawned it ....
}

有意义吗?一般的想法是使用static 函数和传递的this 指针来连接回类的特定实例。

【讨论】:

  • 非常感谢。这正是我想要的。 :)
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 2015-03-03
  • 2015-09-25
  • 2019-12-16
  • 2011-06-20
  • 2015-11-03
  • 2014-04-03
  • 2011-12-13
相关资源
最近更新 更多