Modifying data in threads

2019-06-05 22:48发布

问题:

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?

回答1:

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



回答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