2010-07-27 93 views
1

我有我自己的DLL被注入到另一个进程中。从另一个进程中,DLL通过boost::message_queue将IPC消息发送到我的应用程序。我使用的std :: stringstream的构造消息,如下:std :: stringstream错误?

class Client 
{ 
    ... 

    private: 
     template <class T> void AddMessageParameter(const T &m) 
     { 
      _message &lt&lt m &lt&lt "|"; 
     } 

     void SendMessage() 
     { 
      if (_mq && _message.str().length() < 1024) { 
       // Do not send the same message again. 

       if (_mq_last_sent_message != _message.str()) { 
        _mq_last_sent_message = _message.str(); 

        try { 
         unsigned int tries = 0; 

         // Try send the message five times before giving up. 

         do { 
          if (_mq->try_send(_mq_last_sent_message.c_str(), _mq_last_sent_message.length(), 0)) 
           tries = 5; 
          else 
           ::Sleep(128); 

          ++tries; 
         } while (tries < 5); 
        } catch (...) { 
         // TODO: Add log4cxx logging here for errors... 
        } 
       } 
      } 

      // Clear the message for a new one. 

      _message.seekp(0); 
      _message.clear(); 
      _message.str(std::string()); 
     } 

    private: 
     std::stringstream _message; 
     std::string _mq_last_sent_message; 
     boost::shared_ptr<boost::interprocess::message_queue> _mq; 
}; 

在DLL中,该函数的一个发送以下消息不断:

AddMessageParameter("CLIENT__TABLE__PLAYER_BANKROLL"); 
AddMessageParameter(window_handle); 
AddMessageParameter(seat); 
AddMessageParameter(s); 

SendMessage(); 

现在,这会产生这样的消息CLIENT_TABLE_PLAYER_BANKROLL|00211606|6|€1.28|。问题是,在每几千条消息中,第一个参数不会在那里添加,并且消息变得像00211606|6|€1.28|

这是为什么?这是std :: stringstream中的一些错误,或者我可能做错了什么?

在此先感谢您的帮助。

编辑:

问题解决了。这是一个线程安全问题。一个简单的互斥体解决了这个问题。

回答

11

尝试发送最长的消息时,您的代码失败。因此,我认为消息目标不够快。

我认为你尝试5次的概念是有缺陷的,因为如果它没有发送,你就会吞下你的消息 - 而且你甚至不处理这个严重的错误情况。 我个人建议要么永远等待发送消息,要么建立一个理智的本地缓冲区,这个缓冲区可以工作 - 如果这个缓冲区已满,那么你永远等待。

我也建议你不要吃掉所有的例外而不关心它们。你默默地隐藏严重的错误。

附注: 人们经常认为std :: string有错误,或者操作系统有错误,甚至编译器有错误。 让我向你们保证,这些人在他们的指控中经常犯错,即使是最防守的悲观主义者也会说他们总是错误。 而那些正确的人可以在微不足道的程序中证明它。

请原谅我的傲慢。

+5

+1对于旁注 – onof 2010-07-27 11:40:58

+1

另一个为旁注+1。 – 2010-07-27 12:35:20