c++11的thread庫大大方便了開發,但是目前網絡上少有深入分析的資料和使用例程。特別是在線程函數傳參這一塊,一般止步於使用std::ref傳引用。
這次寫服務器遇到個BUG,線程函數參數是智能指針,傳遞方式是pass by value, 設想的是引用計數+1,但是實質上是引用計數+2。一個在於內部tuple存儲是用的拷貝構造,然后函數調用的時候也是用的拷貝構造。但是實質上不僅僅這2次拷貝構造。寫了斷代碼測試了下。
#include <iostream> #include <memory> #include <thread> using namespace std; class MyClass { public: MyClass(){}; ~MyClass(){ cout << "destruct" << endl; }; MyClass(const MyClass& my){ cout << "copy" << endl; } }; void test(MyClass my) { while (true) { } } int main() { MyClass my; thread t(test, my); t.detach(); while (1) { } return 0; }
輸出如下
進行了5次拷貝構造,3次析構。這是thread隱藏的細節部分。具體是怎樣的,等我把源碼讀懂了再來寫。標准庫的源碼風格看着真的頭大。
經過測試,只會調用拷貝構造,不會調用賦值操作符。