代码之家  ›  专栏  ›  技术社区  ›  Hummingbird

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

  •  2
  • Hummingbird  · 技术社区  · 10 年前

    我需要创建一个基于事件的多线程应用程序,我正在尝试使用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中等待,但我没有收到任何消息,直到发送函数输入和代码崩溃,打印才会出现。 请指导我我做错了什么,如果方法完全错误,我愿意采取新的方法。

    注:这是我第一个关于堆栈溢出的问题,如果我在任何地方迷路了,请纠正。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Jonathan Wakely    10 年前
    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不需要将所有内容都作为 无效* 那是功能吗 static ? 不需要:

    struct XYZ {
      void threadFunc();
      void create();
      void recv();
    };
    
    void XYZ::threadFunc()
    {
      recv();
    }
    
    void XYZ::create()
    {
      boost::thread thr(&XYZ::threadFunc, this);
      thr.join();
    }