今天想到一個問題:如果用類成員函數作為線程函數,那么當線程還在執行的過程中,這個類對象析構了會怎么樣。動手寫個小程序試試,畢竟實踐是檢驗真理的唯一標准么。
#include <iostream> #include <thread> class ThreadTest { public: int i; void Process() { i = 0; while (true) { std::cout << i++ << std::endl; Sleep(1000); } } }; int main() { ThreadTest* test = new ThreadTest(); std::thread thr(&ThreadTest::Process, test); Sleep(5000); test->i = 100; Sleep(5000); delete test; getchar(); }
運行結果如下:-572662304這個會一直打印,除非主程序退出。
就是這么回事,兩個線程公用一個對象,所以在使用類對象時要時刻注意數據安全。