Modifying data in threads

懵懂的女人 提交于 2020-01-03 03:01:11

问题


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



来源:https://stackoverflow.com/questions/10737625/modifying-data-in-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!