1

I have a class with the following structure:

class Nginx_sender
{
    private:
        std::vector<std::string> mMessagesBuffer;
        boost::mutex mMutex;

       void SendMessage(const std::string &msg)
       {
           mMutex.lock();
           mMessagesBuffer.push_back(msg);
           mMutex.unlock();

           std::cout << "Vector size: " << mMessagesBuffer.size() << std::endl;
       }

       void NewThreadFunction()
       {
          while(true) {
            mMutex.lock();
            if (mMessagesBuffer.size() >= 1) std::cout << ">=1\n";
            mMutex.unlock();

            boost::this_thread::sleep(boost::posix_time::milliseconds(200));
          }
       }
};

int main()
{
   Nginx_sender *NginxSenderHandle;
   boost::thread sender(boost::bind(&Nginx_sender::NewThreadFunction, &NginxSenderHandle));
   // ...
}

NewThreadFunction is running in new thread and it checks the size of mMessagesBuffer. Now I call anywhere in main function: NginxSenderHandle->SendMessage("Test");

This shows up: Vector size: 1 first time, 2 second time etc.

But! In NewThreadFunction it's always == 0. Why could it be?

Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • You should only check the buffer size while holding the mutex, as in, print or save to a local variable the value of `mMessagesBuffer.size()`. See what happens then. – EmeryBerger May 24 '12 at 13:05
  • 1
    Are you absolutely sure that you haven't accidentally created two `Nginx_sender`s? Post a complete `main` which exhibits the behaviour. – molbdnilo May 24 '12 at 14:42

2 Answers2

2

You are most probably creating another copy of Nginx_sender when you bind it. Do you really need to reference NginxSenderHandle before passing it to bind() (it's already a pointer)? http://www.boost.org/doc/libs/1_49_0/libs/bind/bind.html#with_member_pointers

Slugart
  • 4,535
  • 24
  • 32
1

I bet compiler is caching some of mMessagesBuffer internals in thread-local cache. Try adding 'volatile' keyword to mMessagesBuffer to disable such optimizations.