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++ 编译没有出现这个错误,特此记录