2009-12-01 76 views
3

我有以下代碼(這是一些半須藤代碼,這可能不是編譯):如何從boost線程訪問我的類實例?

class FooBar { 
public: 
    void a(); 
    void b(); 
    boost::shared_ptr<boost::thread> m_thread; 
    std::string m_test; 
}; 

void FooBar::a() { 
    m_test = "Foo bar" 
    m_thread = shared_ptr<thread>(new thread(bind(&FooBar::b, this))); 
} 

void FooBar::b() { 
    cout << m_test; 
} 

代碼cout << test不產生任何輸出,因爲m_test""代替"Foo bar"。爲什麼是這樣?我認爲通過this作爲bind的第二個參數將允許我從b()訪問相同的實例 - 我錯了嗎?

回答

6

是的,那有效。這裏是「真實」的版本,這的確實際上打印「富巴」:

#include <boost/make_shared.hpp> 
#include <boost/thread.hpp> 
#include <boost/bind.hpp> 

using namespace boost; 

struct FooBar { 
    void a(); 
    void b(); 
    shared_ptr<thread> m_thread; 
    std::string m_test; 
}; 

void FooBar::a() { 
    m_test = "Foo bar"; 
    m_thread = make_shared<thread>(bind(&FooBar::b, this)); 
} 

void FooBar::b() { 
    std::cout << m_test; 
} 

int main() { 
    FooBar fb; 
    fb.a(); 
    fb.m_thread->join(); 
    return 0; 
} 

代碼cout << test不會產生任何輸出,因爲m_test是「」

我懷疑這是因爲在線程開始評​​估成員變量之前,對象正在被銷燬。請注意0​​,這非常重要。

+0

非常感謝發佈工作代碼!是的,我在析構函數中放置了一個斷點,然後嘿,直到我用靜態單例的完整類型而不是指針 - 噢!所以每次我打電話給單身人士時都會創建一個新實例。現在修復,再次感謝您的代碼。 – 2009-12-01 17:50:49