无法使用Boost线程中的message_queue接收消息

Unable to receive a message using message_queue in Boost thread

本文关键字:message queue 消息 Boost 线程      更新时间:2023-10-16

我需要创建一个基于事件的多线程应用程序,我正尝试使用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();
}