0

this is the next step after this topic: Modifying data in threads

class Nginx_sender
{
    private:
        std::atomic_int data;
        boost::mutex mMutex;
   void SendMessage(const std::string &msg)
   {
       mMutex.lock();
       data++;
       mMutex.unlock();

       std::cout << "DATA: " << data << std::endl;
   }

   void NewThreadFunction()
   {
      while(true) {
        mMutex.lock();
         std::cout << data;
        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));
   // ...
}

In NewThreadFunction the data is always 0 and in SendMessage it changes each time I call SendMessage. So, what's the right way to work with this?

Community
  • 1
  • 1
Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • You're passing the address of a local variable to another thread, which is a bad idea. In your case it might work out, because `main` doesn't return until the program (and the other thread) exits, but you should consider dynamic allocation for this. – Ben Voigt May 24 '12 at 13:44

2 Answers2

2

Why are you passing a Nginx_sender ** (double pointer) to boost::bind? That seems wrong, and would explain why your thread appears to be operating on a second copy of the object than the main thread.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

Remove the & from the second argument to bind. You already have a pointer to the object, and that's what you're likely trying to use. Secondly, the pointer is uninitialized which could also be a source of you problem. Note, you'll have to be sure the object remains valid until the thread is joined.

int main()
{
   Nginx_sender *NginxSenderHandle = new Nginx_sender  ;
   boost::thread sender(boost::bind(&Nginx_sender::NewThreadFunction, NginxSenderHandle));
   // ...
}
Dave S
  • 20,507
  • 3
  • 48
  • 68