我已經挖掘了各種書籍和在線資源,但仍然不確定如何處理這種情況一個不斷循環的成員函數可能會啓動一個可能需要訪問其他成員函數和變量的新線程(並且有時會對它們進行變異)。下面的代碼描述的情況:在成員函數中正確捕獲(lambda)和安全問題開始一個新的線程(C++ 11/14)
class Foo {
int read_only;
Object some_big_object;
std::atomic<int> read_and_write;
// more private member variables
void helper_function_a(const Object& value) {
Object copy = value.clone(); // deep copy
std::thread t {[/*what should I put here?*/](){
// read from read_only and WRITE to read_and_write
if (/*some condition which is occasionally true*/)
helper_function_b(copy);
}};
t.detach();
}
void helper_function_b(const Object& value) {
// change value
}
public:
void update() {
// update some_big_object;
// read from read_only and READ OR WRITE from/to read_and_write
helper_function_a(some_big_object);
}
void doSomething;
};
int main() {
Foo f;
while (true) {
f.update();
}
}
我知道,我可以把this
成員函數中捕捉到的一切,但我真的不希望捕捉到一切,只是我用,如果有可能的事情,沒有其他的。我真正的類更復雜,也具有應該保持不變的變量,但我不能聲明const(因爲我在構造函數的主體中初始化了它們) - 確保lambda只能訪問它使用的東西。那麼我應該在那裏放什麼?
那麼這個設計呢?感覺不對 - 但是它?爲什麼?請注意,在我真正的課程(這是更復雜)helper_function_a
失敗 - 我仍然不確定錯誤的確切位置,但如果我刪除lambda並使其單線程它可以工作。在我的應用程序中,我使用helper_function_a在更新動畫時執行大對象的文件IO - 它不覺得寫入來執行來自同一線程的兩個任務。
最後,我可以安全使用read_and_write嗎?
如果要使用類的成員,您必須捕獲'this',那麼真的沒有辦法繞過它。 –
你的代碼調用'helper_function_b(...)'(一種方法)...並且你不想捕獲'this'? – 6502
我一直在想''(this-> helper_function_b)'(當然不會編譯)。但是你的意見使得它相當明確,沒有辦法解決它.. –