## Run `sudo apt-get install -y nodejs` to install Node.js 10.x and npm ## You may also need development tools to build native addons: sudo apt-get install gcc g++ make ## To install the Yarn package manager, run: curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list sudo apt-get update && sudo apt-get install yarn
voidmyfunc(int& n){ std::cout << "myfunc n=" << n << '\n'; n++; } intmain(){ int n = 0; std::thread t1(myfunc, n); t1.join(); std::cout << "main n=" << n << '\n'; return0; }
疑?!結果居然出現編譯錯誤,
1 2 3 4 5 6 7 8 9
/usr/include/c++/5/functional: In instantiation of ‘struct std::_Bind_simple<void (*(int))(int&)>’: /usr/include/c++/5/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&); _Args = {int&}]’ std-ref4.cpp:12:29: required from here /usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’ typedef typename result_of<_Callable(_Args...)>::type result_type; ^ /usr/include/c++/5/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’ _M_invoke(_Index_tuple<_Indices...>) ^
voidmyfunc(int& n){ std::cout << "myfunc n=" << n << '\n'; n++; } intmain(){ int n = 0; std::thread t1(myfunc, std::ref(n)); t1.join(); std::cout << "main n=" << n << '\n'; return0; }
馬上在 std::thread 開執行緒時傳遞參數改成 std::ref(n) 就可以編譯成功了,輸出結果如下,由此可見 std::thread() 預設使用的是參數傳遞方式是傳值 call by value 而不是傳參考 call by reference,關於 call by value 與 call by reference 這兩個的參數傳遞差異可以看這篇。