无法使用Boost线程中的message_queue接收消息
Unable to receive a message using message_queue in Boost thread
我需要创建一个基于事件的多线程应用程序,我正尝试使用boost::thread和boost/interprocess/ipc/message_queue在线程之间发送消息。我目前正在做的是让线程在其workerfunction中等待消息。实际上,这只是一个基本的开始,发送方和接收方都是同一个线程,在稍后的阶段,我想存储一个对应于每个线程的message_queue列表,然后相应地获取它或类似的东西。但现在,根据下面的代码,我正在使用
//in a common class
typedef struct s_Request{
int id;
}st_Request;
//in thread(XYZ) class
st_Request dataone;
message_queue *mq;
void XYZ::threadfunc(void *ptr)
{
XYZ*obj = (XYZ*) ptr;
obj->RecieveMsg();
}
void XYZ::RecieveMsg()
{
message_queue mq1(open_only,"message_queue");
if(!(mq1.try_receive(&dataone, sizeof(st_Request), recvd_size, priority)))
printf("msg not received");
printf("id = %d",dataone.id);
}
void XYZ::Create()
{
mq= new message_queue(open_or_create,"message_queue",100,sizeof(st_Request));
boost:thread workerthread(threadfunc,this);
workerthread.join();
}
void XYZ::Send(st_Request *data)
{
if (!(mq->try_send(data, sizeof(st_Request), 0)))
printf("message sending failed");
}
//I am calling it like
class ABC: public XYZ
{
..some functions to do stuff... };
void ABC::createMSGQ()
{
create();
st_Request *data;
data->id =10;
send(data);
}
我的线程正在RecieveMsg中等待,但我没有收到任何消息,直到发送函数输入和代码崩溃后,打印才会出现。请指导我做错了什么,如果方法完全错误,我愿意采取新的方法。
附言:这是我关于堆栈溢出的第一个问题,我试着遵循指导原则,但如果我偏离了任何地方,请纠正。
st_Request *data;
data->id =10;
data
未初始化,您不能取消引用它。指针在取消引用之前应该指向某个对象。
我不明白这个功能的意义:
void XYZ::Create()
{
mq= new message_queue(open_or_create,"message_queue",100,sizeof(st_Request));
boost:thread workerthread(threadfunc,this);
workerthread.join();
}
你创建了一个新的线程,然后阻塞并等待它完成,这样你就可以加入它了。为什么不在这里做这项工作,而不是创建一个新线程并等待它结束呢?
什么是threadfunc
?你是说ThreadFunc
吗?
这个函数写得很奇怪:
void XYZ::ThreadFunc(void *ptr)
{
XYZ*obj = (XYZ*) ptr;
obj->RecieveMsg();
}
为什么不将参数作为XYZ*
而不是void*
传递呢?Boost.Thread并不要求所有内容都作为void*
传递。那个函数是static
吗?不需要:
struct XYZ {
void threadFunc();
void create();
void recv();
};
void XYZ::threadFunc()
{
recv();
}
void XYZ::create()
{
boost::thread thr(&XYZ::threadFunc, this);
thr.join();
}
相关文章:
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- C++ queue.front();为什么不从第一个元素开始呢?
- 为什么构造函数 Message(const T&data) 与 Message(T&& data) 冲突,当 T = int&时?
- 我可以擦除 std::queue 中间的节点吗?
- 获取大小时是否必须锁定 std::queue?
- AMQP-CPP RabbitMQ 接收额外的符号 message.body() 比 message.size() 大
- char array[sizeof(Message)]; vs char* array = new char[sizeo
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- 销毁 std::queue 会导致内存错误
- Protobuf:无法在 message.pb.h 文件中打开包含文件 common.h
- 如何将一个 std::queue 的内容附加到另一个
- 使用元素加载 std::queue<uint8_t*> 的更有效方法?
- 为什么 std::queue 没有实现 insert() 而 std::d eque 实现了?
- 带有 std::vector 和 std::queue 的 Prim's 算法,我的代码有什么问题?
- C++程序在 #include 时无法编译<stack>,#include<queue>
- 从 recv() 读取多个"message"
- 是boost :: lockfree :: Queue(在多线程程序中)可锁定
- Android Studio 3.2:cmake message()输出显示在哪里
- 对在协议缓冲区中使用 Message::P arseFromIstream 感到困惑