Reputation: 64266
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?
Upvotes: 0
Views: 275
Reputation: 21058
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));
// ...
}
Upvotes: 1
Reputation: 283624
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.
Upvotes: 2