简体   繁体   English

原子类型和线程

[英]Atomic types and threads

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 . NewThreadFunction ,数据始终为0,而​​在SendMessage ,每次我调用SendMessage时数据都会更改。 So, what's the right way to work with this? 那么,什么是正确的方法呢?

Why are you passing a Nginx_sender ** (double pointer) to boost::bind ? 为什么要传递Nginx_sender ** (双指针)以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. 这似乎是错误的,并且可以解释为什么您的线程似乎在对象的第二个副本上而不是在主线程上运行。

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));
   // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM