Wednesday, 15 January 2014

c++ - How can I access my class instance from a boost thread? -


I have the following code (this is some semi-pseudo code that can not be compiled):

  class FooBar {public: zero A (); Zero b (); Promote: shared_ptr & lt; Boost: Thread & gt; M_thread; Std :: string m_test; }; Zero FooBar :: a () {m_test = "Foo bar" m_thread = shared_ptr & lt; Thread & gt; (New thread (Tie (& FooBar :: b, this))); } Zero FooBar :: b () {cout & lt; & Lt; M_test; }  

Code cout < & Lt; Instead of "foo bar" , "" is . Why is it like this? I think that going to be the second argument of this to bind would allow me to enter from the same example with b () - Am I wrong?

Yes, it works here is the "real" version, which in fact print "Foo Bar" Does:

  #include & lt; Boost / make_shared.hpp & gt; # Include & lt; Boost / thread.hpp & gt; # Include & lt; Boost / bind.hpp & gt; Using Namespace Boost; Structure will be canceled {Cancel}; Zero b (); Shared_ptr & lt; Thread & gt; M_thread; Std :: string m_test; }; Zero FooBar :: a () {m_test = "Foo bar"; M_thread = make_shared & lt; Thread & gt; (Tie (and Full :: B, it)); } Zero FooBar :: b () {std :: cout & lt; & Lt; M_test; } Int main () {FooBar fb; Fb.a (); Fb.m_thread- & gt; joining in (); Return 0; }  

Code cout < & Lt; Test does not produce any output, because m_test is ""

I suspect that the thread is thrown before the object is destroyed Note the member variable evaluation was found join () , it is very important.


No comments:

Post a Comment