2019獨角獸企業重金招聘Python工程師標準>>>
[hadoop@iZ25s7cmfyrZ C_script]$ cat test_thread_a.cpp
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>std::atomic<int> global_counter(0);void increase_global (int n){for (int i=0; i< n; ++i)++global_counter;
}void increase_reference(std::atomic<int>& variable, int n){for (int i=0;i<n; ++i)++variable;
}struct C:std::atomic<int>{C():std::atomic<int>(0){}void increase_member(int n){for(int i=0;i<n;++i)fetch_add(1);}
};int main(int argc, char** argv){std::vector<std::thread> threads;std::cout << "Increase global counter with 10 threads...." << std::endl;for(int i=0;i<10;++i)threads.push_back(std::thread(increase_global, 1000));std::cout << "Increase counter (foo) with 10 threads using reference...\n";std::atomic<int> foo(0);for(int i=0;i<10;++i)threads.push_back(std::thread(increase_reference, std::ref(foo), 1000));std::cout << "Increase counter (bar) with 10 threads using member...\n";C bar{};for(int i=0;i<10;++i){threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));}std::cout << "synchronizing all threads...\n";for(auto& th:threads) th.join();std::cout << "global: " << global_counter << std::endl;std::cout << "foo: " << foo << std::endl;std::cout << "bar: " << bar << std::endl;
}
使用 ?g++ 編譯上面的代碼,結果因為存在歧義 將C bar{}(注有無{}都報這個錯誤) 將bar理解成一個 返回C 類型的函數, 文章中說https://en.wikipedia.org/wiki/Most_vexing_parse, 在c++11中已經修復這個錯誤,就是在 變量后面添加花括號, 但是沒有用依然報錯,
In file included from /usr/include/c++/4.8.2/thread:39:0,from test_thread_a.cpp:3:
/usr/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’:
/usr/include/c++/4.8.2/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (C::*)(int); _Args = {std::reference_wrapper<C>, int}]’
test_thread_a.cpp:42:77: required from here
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’typedef typename result_of<_Callable(_Args...)>::type result_type;^
/usr/include/c++/4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’_M_invoke(_Index_tuple<_Indices...>)
后來改用 clang++ 編譯沒有出現這個錯誤,特此記錄