如何使用postThreadMessage传递一个struct [英] how to use postThreadMessage to pass a struct

查看:605
本文介绍了如何使用postThreadMessage传递一个struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用Windows的消息队列设施,以一个struct发送到另一个线程。
但我发现,在postthreadmessage功能只提供两个整数参数,wParam和lParam我通过arguments.So我决定把该结构的地址lparam中。这是正确的方式使用的窗口传递结构?

I want to use windows's message queue facilities to send a struct to another thread. But I find out that the postthreadmessage function only provide two integer parameters, lparam and wparam for me to pass arguments.So I decide to put the address of the struct in lparam. Is this the correct way windows use to pass struct?

和我打算使用boost :: shared_ptr的持有结构的地址,同时在接收线程和发送者线程。我怀疑,当两个shared_ptrs超出范围,将在结构被释放两次?我不能想出一个办法,以确保堆上分配将被100%释放的结构,任何想法?

And I intend to use boost::shared_ptr to hold the address of struct in both the receiver thread and sender thread. I doubt that when the two shared_ptrs goes out of scope, will the struct be freed twice? I can not figure out a way to ensure the struct allocated on heap will be 100% freed, Any ideas?

推荐答案

要第一个问题,是的,LPARAM是打算用来为一个整数或一个指针。这是明确的自定义:

To the first question, yes, LPARAM is intended to be used as an integer or a pointer. That is clear from the definition:

typedef LONG_PTR LPARAM;

这是足够长,以容纳一个指针的整数。

That is an integer long enough to hold a pointer.

关于shared_ptr的事情,你是对的,如果传递的原始指针,并将其包装成另一个shared_ptr的,你会释放它两次:

About the shared_ptr thing, you are right, if you pass the raw pointer and wrap it into another shared_ptr you will free it twice:

shared_ptr<Thing> a;
PostThreadMessage(x, 0, (LPARAM)a.get());
...
LRESULT OnMessage(int msg, WPARAM wp, LPARAM lp)
{
    shared_ptr<Thing> p((Thing*)lp); //Bad!!!
}

不过你可以试试这个解决方法,而不是:

But you can try this workaround instead:

shared_ptr<Thing> a;
PostThreadMessage(x, 0, new shared_ptr<Thing>(a)); //pointer to smart-pointer
...
LRESULT OnMessage(int msg, WPARAM wp, LPARAM lp)
{
    shared_ptr<Thing> *pp = (shared_ptr<Thing>*)lp;
    shared_ptr<Thing> p(*pp);
    delete pp; //no leak
}

事后:注意PostThreadMessage可能会失败......你不想泄露一个shared_ptr

AFTERTHOUGHT: Note that PostThreadMessage may fail... and you don't want to leak a shared_ptr.

在我的经验,一般最好使用一个std ::双端队列来保存数据,并使用PostThreadMessage来通知有数据存在。这样你永远不会失去的对象!因人而异

In my experience it is generally better to use a std::deque to hold the data and use the PostThreadMessage to notify that there is data there. In this way you'll never lose an object! YMMV

这篇关于如何使用postThreadMessage传递一个struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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