enumerable_thread_specific.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. /*
  2. Copyright (c) 2005-2020 Intel Corporation
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #ifndef __TBB_enumerable_thread_specific_H
  14. #define __TBB_enumerable_thread_specific_H
  15. #define __TBB_enumerable_thread_specific_H_include_area
  16. #include "internal/_warning_suppress_enable_notice.h"
  17. #include "atomic.h"
  18. #include "concurrent_vector.h"
  19. #include "tbb_thread.h"
  20. #include "tbb_allocator.h"
  21. #include "cache_aligned_allocator.h"
  22. #include "aligned_space.h"
  23. #include "internal/_template_helpers.h"
  24. #include "internal/_tbb_hash_compare_impl.h"
  25. #include "tbb_profiling.h"
  26. #include <string.h> // for memcpy
  27. #if __TBB_PREVIEW_RESUMABLE_TASKS
  28. #include "task.h" // for task::suspend_point
  29. #endif
  30. #if _WIN32||_WIN64
  31. #include "machine/windows_api.h"
  32. #else
  33. #include <pthread.h>
  34. #endif
  35. #define __TBB_ETS_USE_CPP11 \
  36. (__TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT \
  37. && __TBB_CPP11_DECLTYPE_PRESENT && __TBB_CPP11_LAMBDAS_PRESENT)
  38. namespace tbb {
  39. //! enum for selecting between single key and key-per-instance versions
  40. enum ets_key_usage_type {
  41. ets_key_per_instance
  42. , ets_no_key
  43. #if __TBB_PREVIEW_RESUMABLE_TASKS
  44. , ets_suspend_aware
  45. #endif
  46. };
  47. namespace interface6 {
  48. // Forward declaration to use in internal classes
  49. template <typename T, typename Allocator, ets_key_usage_type ETS_key_type>
  50. class enumerable_thread_specific;
  51. //! @cond
  52. namespace internal {
  53. using namespace tbb::internal;
  54. template <ets_key_usage_type ETS_key_type>
  55. struct ets_key_selector {
  56. typedef tbb_thread::id key_type;
  57. static key_type current_key() {
  58. return tbb::internal::thread_get_id_v3();
  59. }
  60. };
  61. #if __TBB_PREVIEW_RESUMABLE_TASKS
  62. template <>
  63. struct ets_key_selector<ets_suspend_aware> {
  64. typedef task::suspend_point key_type;
  65. static key_type current_key() {
  66. return internal_current_suspend_point();
  67. }
  68. };
  69. inline task::suspend_point atomic_compare_and_swap(task::suspend_point& location,
  70. const task::suspend_point& value, const task::suspend_point& comparand) {
  71. return as_atomic(location).compare_and_swap(value, comparand);
  72. }
  73. #endif
  74. template<ets_key_usage_type ETS_key_type>
  75. class ets_base: tbb::internal::no_copy {
  76. protected:
  77. typedef typename ets_key_selector<ETS_key_type>::key_type key_type;
  78. #if __TBB_PROTECTED_NESTED_CLASS_BROKEN
  79. public:
  80. #endif
  81. struct slot;
  82. struct array {
  83. array* next;
  84. size_t lg_size;
  85. slot& at( size_t k ) {
  86. return ((slot*)(void*)(this+1))[k];
  87. }
  88. size_t size() const {return size_t(1)<<lg_size;}
  89. size_t mask() const {return size()-1;}
  90. size_t start( size_t h ) const {
  91. return h>>(8*sizeof(size_t)-lg_size);
  92. }
  93. };
  94. struct slot {
  95. key_type key;
  96. void* ptr;
  97. bool empty() const {return key == key_type();}
  98. bool match( key_type k ) const {return key == k;}
  99. bool claim( key_type k ) {
  100. // TODO: maybe claim ptr, because key_type is not guaranteed to fit into word size
  101. return atomic_compare_and_swap(key, k, key_type()) == key_type();
  102. }
  103. };
  104. #if __TBB_PROTECTED_NESTED_CLASS_BROKEN
  105. protected:
  106. #endif
  107. //! Root of linked list of arrays of decreasing size.
  108. /** NULL if and only if my_count==0.
  109. Each array in the list is half the size of its predecessor. */
  110. atomic<array*> my_root;
  111. atomic<size_t> my_count;
  112. virtual void* create_local() = 0;
  113. virtual void* create_array(size_t _size) = 0; // _size in bytes
  114. virtual void free_array(void* ptr, size_t _size) = 0; // _size in bytes
  115. array* allocate( size_t lg_size ) {
  116. size_t n = size_t(1)<<lg_size;
  117. array* a = static_cast<array*>(create_array( sizeof(array)+n*sizeof(slot) ));
  118. a->lg_size = lg_size;
  119. std::memset( a+1, 0, n*sizeof(slot) );
  120. return a;
  121. }
  122. void free(array* a) {
  123. size_t n = size_t(1)<<(a->lg_size);
  124. free_array( (void *)a, size_t(sizeof(array)+n*sizeof(slot)) );
  125. }
  126. ets_base() {my_root=NULL; my_count=0;}
  127. virtual ~ets_base(); // g++ complains if this is not virtual
  128. void* table_lookup( bool& exists );
  129. void table_clear();
  130. // The following functions are not used in concurrent context,
  131. // so we don't need synchronization and ITT annotations there.
  132. template <ets_key_usage_type E2>
  133. void table_elementwise_copy( const ets_base& other,
  134. void*(*add_element)(ets_base<E2>&, void*) ) {
  135. __TBB_ASSERT(!my_root,NULL);
  136. __TBB_ASSERT(!my_count,NULL);
  137. if( !other.my_root ) return;
  138. array* root = my_root = allocate(other.my_root->lg_size);
  139. root->next = NULL;
  140. my_count = other.my_count;
  141. size_t mask = root->mask();
  142. for( array* r=other.my_root; r; r=r->next ) {
  143. for( size_t i=0; i<r->size(); ++i ) {
  144. slot& s1 = r->at(i);
  145. if( !s1.empty() ) {
  146. for( size_t j = root->start(tbb::tbb_hash<key_type>()(s1.key)); ; j=(j+1)&mask ) {
  147. slot& s2 = root->at(j);
  148. if( s2.empty() ) {
  149. s2.ptr = add_element(static_cast<ets_base<E2>&>(*this), s1.ptr);
  150. s2.key = s1.key;
  151. break;
  152. }
  153. else if( s2.match(s1.key) )
  154. break;
  155. }
  156. }
  157. }
  158. }
  159. }
  160. void table_swap( ets_base& other ) {
  161. __TBB_ASSERT(this!=&other, "Don't swap an instance with itself");
  162. tbb::internal::swap<relaxed>(my_root, other.my_root);
  163. tbb::internal::swap<relaxed>(my_count, other.my_count);
  164. }
  165. };
  166. template<ets_key_usage_type ETS_key_type>
  167. ets_base<ETS_key_type>::~ets_base() {
  168. __TBB_ASSERT(!my_root, NULL);
  169. }
  170. template<ets_key_usage_type ETS_key_type>
  171. void ets_base<ETS_key_type>::table_clear() {
  172. while( array* r = my_root ) {
  173. my_root = r->next;
  174. free(r);
  175. }
  176. my_count = 0;
  177. }
  178. template<ets_key_usage_type ETS_key_type>
  179. void* ets_base<ETS_key_type>::table_lookup( bool& exists ) {
  180. const key_type k = ets_key_selector<ETS_key_type>::current_key();
  181. __TBB_ASSERT(k != key_type(),NULL);
  182. void* found;
  183. size_t h = tbb::tbb_hash<key_type>()(k);
  184. for( array* r=my_root; r; r=r->next ) {
  185. call_itt_notify(acquired,r);
  186. size_t mask=r->mask();
  187. for(size_t i = r->start(h); ;i=(i+1)&mask) {
  188. slot& s = r->at(i);
  189. if( s.empty() ) break;
  190. if( s.match(k) ) {
  191. if( r==my_root ) {
  192. // Success at top level
  193. exists = true;
  194. return s.ptr;
  195. } else {
  196. // Success at some other level. Need to insert at top level.
  197. exists = true;
  198. found = s.ptr;
  199. goto insert;
  200. }
  201. }
  202. }
  203. }
  204. // Key does not yet exist. The density of slots in the table does not exceed 0.5,
  205. // for if this will occur a new table is allocated with double the current table
  206. // size, which is swapped in as the new root table. So an empty slot is guaranteed.
  207. exists = false;
  208. found = create_local();
  209. {
  210. size_t c = ++my_count;
  211. array* r = my_root;
  212. call_itt_notify(acquired,r);
  213. if( !r || c>r->size()/2 ) {
  214. size_t s = r ? r->lg_size : 2;
  215. while( c>size_t(1)<<(s-1) ) ++s;
  216. array* a = allocate(s);
  217. for(;;) {
  218. a->next = r;
  219. call_itt_notify(releasing,a);
  220. array* new_r = my_root.compare_and_swap(a,r);
  221. if( new_r==r ) break;
  222. call_itt_notify(acquired, new_r);
  223. if( new_r->lg_size>=s ) {
  224. // Another thread inserted an equal or bigger array, so our array is superfluous.
  225. free(a);
  226. break;
  227. }
  228. r = new_r;
  229. }
  230. }
  231. }
  232. insert:
  233. // Whether a slot has been found in an older table, or if it has been inserted at this level,
  234. // it has already been accounted for in the total. Guaranteed to be room for it, and it is
  235. // not present, so search for empty slot and use it.
  236. array* ir = my_root;
  237. call_itt_notify(acquired, ir);
  238. size_t mask = ir->mask();
  239. for(size_t i = ir->start(h);;i=(i+1)&mask) {
  240. slot& s = ir->at(i);
  241. if( s.empty() ) {
  242. if( s.claim(k) ) {
  243. s.ptr = found;
  244. return found;
  245. }
  246. }
  247. }
  248. }
  249. //! Specialization that exploits native TLS
  250. template <>
  251. class ets_base<ets_key_per_instance>: public ets_base<ets_no_key> {
  252. typedef ets_base<ets_no_key> super;
  253. #if _WIN32||_WIN64
  254. #if __TBB_WIN8UI_SUPPORT
  255. typedef DWORD tls_key_t;
  256. void create_key() { my_key = FlsAlloc(NULL); }
  257. void destroy_key() { FlsFree(my_key); }
  258. void set_tls(void * value) { FlsSetValue(my_key, (LPVOID)value); }
  259. void* get_tls() { return (void *)FlsGetValue(my_key); }
  260. #else
  261. typedef DWORD tls_key_t;
  262. void create_key() { my_key = TlsAlloc(); }
  263. void destroy_key() { TlsFree(my_key); }
  264. void set_tls(void * value) { TlsSetValue(my_key, (LPVOID)value); }
  265. void* get_tls() { return (void *)TlsGetValue(my_key); }
  266. #endif
  267. #else
  268. typedef pthread_key_t tls_key_t;
  269. void create_key() { pthread_key_create(&my_key, NULL); }
  270. void destroy_key() { pthread_key_delete(my_key); }
  271. void set_tls( void * value ) const { pthread_setspecific(my_key, value); }
  272. void* get_tls() const { return pthread_getspecific(my_key); }
  273. #endif
  274. tls_key_t my_key;
  275. virtual void* create_local() __TBB_override = 0;
  276. virtual void* create_array(size_t _size) __TBB_override = 0; // _size in bytes
  277. virtual void free_array(void* ptr, size_t _size) __TBB_override = 0; // size in bytes
  278. protected:
  279. ets_base() {create_key();}
  280. ~ets_base() {destroy_key();}
  281. void* table_lookup( bool& exists ) {
  282. void* found = get_tls();
  283. if( found ) {
  284. exists=true;
  285. } else {
  286. found = super::table_lookup(exists);
  287. set_tls(found);
  288. }
  289. return found;
  290. }
  291. void table_clear() {
  292. destroy_key();
  293. create_key();
  294. super::table_clear();
  295. }
  296. void table_swap( ets_base& other ) {
  297. using std::swap;
  298. __TBB_ASSERT(this!=&other, "Don't swap an instance with itself");
  299. swap(my_key, other.my_key);
  300. super::table_swap(other);
  301. }
  302. };
  303. //! Random access iterator for traversing the thread local copies.
  304. template< typename Container, typename Value >
  305. class enumerable_thread_specific_iterator
  306. #if defined(_WIN64) && defined(_MSC_VER)
  307. // Ensure that Microsoft's internal template function _Val_type works correctly.
  308. : public std::iterator<std::random_access_iterator_tag,Value>
  309. #endif /* defined(_WIN64) && defined(_MSC_VER) */
  310. {
  311. //! current position in the concurrent_vector
  312. Container *my_container;
  313. typename Container::size_type my_index;
  314. mutable Value *my_value;
  315. template<typename C, typename T>
  316. friend enumerable_thread_specific_iterator<C,T>
  317. operator+( ptrdiff_t offset, const enumerable_thread_specific_iterator<C,T>& v );
  318. template<typename C, typename T, typename U>
  319. friend bool operator==( const enumerable_thread_specific_iterator<C,T>& i,
  320. const enumerable_thread_specific_iterator<C,U>& j );
  321. template<typename C, typename T, typename U>
  322. friend bool operator<( const enumerable_thread_specific_iterator<C,T>& i,
  323. const enumerable_thread_specific_iterator<C,U>& j );
  324. template<typename C, typename T, typename U>
  325. friend ptrdiff_t operator-( const enumerable_thread_specific_iterator<C,T>& i,
  326. const enumerable_thread_specific_iterator<C,U>& j );
  327. template<typename C, typename U>
  328. friend class enumerable_thread_specific_iterator;
  329. public:
  330. enumerable_thread_specific_iterator( const Container &container, typename Container::size_type index ) :
  331. my_container(&const_cast<Container &>(container)), my_index(index), my_value(NULL) {}
  332. //! Default constructor
  333. enumerable_thread_specific_iterator() : my_container(NULL), my_index(0), my_value(NULL) {}
  334. template<typename U>
  335. enumerable_thread_specific_iterator( const enumerable_thread_specific_iterator<Container, U>& other ) :
  336. my_container( other.my_container ), my_index( other.my_index), my_value( const_cast<Value *>(other.my_value) ) {}
  337. enumerable_thread_specific_iterator operator+( ptrdiff_t offset ) const {
  338. return enumerable_thread_specific_iterator(*my_container, my_index + offset);
  339. }
  340. enumerable_thread_specific_iterator &operator+=( ptrdiff_t offset ) {
  341. my_index += offset;
  342. my_value = NULL;
  343. return *this;
  344. }
  345. enumerable_thread_specific_iterator operator-( ptrdiff_t offset ) const {
  346. return enumerable_thread_specific_iterator( *my_container, my_index-offset );
  347. }
  348. enumerable_thread_specific_iterator &operator-=( ptrdiff_t offset ) {
  349. my_index -= offset;
  350. my_value = NULL;
  351. return *this;
  352. }
  353. Value& operator*() const {
  354. Value* value = my_value;
  355. if( !value ) {
  356. value = my_value = (*my_container)[my_index].value();
  357. }
  358. __TBB_ASSERT( value==(*my_container)[my_index].value(), "corrupt cache" );
  359. return *value;
  360. }
  361. Value& operator[]( ptrdiff_t k ) const {
  362. return (*my_container)[my_index + k].value;
  363. }
  364. Value* operator->() const {return &operator*();}
  365. enumerable_thread_specific_iterator& operator++() {
  366. ++my_index;
  367. my_value = NULL;
  368. return *this;
  369. }
  370. enumerable_thread_specific_iterator& operator--() {
  371. --my_index;
  372. my_value = NULL;
  373. return *this;
  374. }
  375. //! Post increment
  376. enumerable_thread_specific_iterator operator++(int) {
  377. enumerable_thread_specific_iterator result = *this;
  378. ++my_index;
  379. my_value = NULL;
  380. return result;
  381. }
  382. //! Post decrement
  383. enumerable_thread_specific_iterator operator--(int) {
  384. enumerable_thread_specific_iterator result = *this;
  385. --my_index;
  386. my_value = NULL;
  387. return result;
  388. }
  389. // STL support
  390. typedef ptrdiff_t difference_type;
  391. typedef Value value_type;
  392. typedef Value* pointer;
  393. typedef Value& reference;
  394. typedef std::random_access_iterator_tag iterator_category;
  395. };
  396. template<typename Container, typename T>
  397. enumerable_thread_specific_iterator<Container,T>
  398. operator+( ptrdiff_t offset, const enumerable_thread_specific_iterator<Container,T>& v ) {
  399. return enumerable_thread_specific_iterator<Container,T>( v.my_container, v.my_index + offset );
  400. }
  401. template<typename Container, typename T, typename U>
  402. bool operator==( const enumerable_thread_specific_iterator<Container,T>& i,
  403. const enumerable_thread_specific_iterator<Container,U>& j ) {
  404. return i.my_index==j.my_index && i.my_container == j.my_container;
  405. }
  406. template<typename Container, typename T, typename U>
  407. bool operator!=( const enumerable_thread_specific_iterator<Container,T>& i,
  408. const enumerable_thread_specific_iterator<Container,U>& j ) {
  409. return !(i==j);
  410. }
  411. template<typename Container, typename T, typename U>
  412. bool operator<( const enumerable_thread_specific_iterator<Container,T>& i,
  413. const enumerable_thread_specific_iterator<Container,U>& j ) {
  414. return i.my_index<j.my_index;
  415. }
  416. template<typename Container, typename T, typename U>
  417. bool operator>( const enumerable_thread_specific_iterator<Container,T>& i,
  418. const enumerable_thread_specific_iterator<Container,U>& j ) {
  419. return j<i;
  420. }
  421. template<typename Container, typename T, typename U>
  422. bool operator>=( const enumerable_thread_specific_iterator<Container,T>& i,
  423. const enumerable_thread_specific_iterator<Container,U>& j ) {
  424. return !(i<j);
  425. }
  426. template<typename Container, typename T, typename U>
  427. bool operator<=( const enumerable_thread_specific_iterator<Container,T>& i,
  428. const enumerable_thread_specific_iterator<Container,U>& j ) {
  429. return !(j<i);
  430. }
  431. template<typename Container, typename T, typename U>
  432. ptrdiff_t operator-( const enumerable_thread_specific_iterator<Container,T>& i,
  433. const enumerable_thread_specific_iterator<Container,U>& j ) {
  434. return i.my_index-j.my_index;
  435. }
  436. template<typename SegmentedContainer, typename Value >
  437. class segmented_iterator
  438. #if defined(_WIN64) && defined(_MSC_VER)
  439. : public std::iterator<std::input_iterator_tag, Value>
  440. #endif
  441. {
  442. template<typename C, typename T, typename U>
  443. friend bool operator==(const segmented_iterator<C,T>& i, const segmented_iterator<C,U>& j);
  444. template<typename C, typename T, typename U>
  445. friend bool operator!=(const segmented_iterator<C,T>& i, const segmented_iterator<C,U>& j);
  446. template<typename C, typename U>
  447. friend class segmented_iterator;
  448. public:
  449. segmented_iterator() {my_segcont = NULL;}
  450. segmented_iterator( const SegmentedContainer& _segmented_container ) :
  451. my_segcont(const_cast<SegmentedContainer*>(&_segmented_container)),
  452. outer_iter(my_segcont->end()) { }
  453. ~segmented_iterator() {}
  454. typedef typename SegmentedContainer::iterator outer_iterator;
  455. typedef typename SegmentedContainer::value_type InnerContainer;
  456. typedef typename InnerContainer::iterator inner_iterator;
  457. // STL support
  458. typedef ptrdiff_t difference_type;
  459. typedef Value value_type;
  460. typedef typename SegmentedContainer::size_type size_type;
  461. typedef Value* pointer;
  462. typedef Value& reference;
  463. typedef std::input_iterator_tag iterator_category;
  464. // Copy Constructor
  465. template<typename U>
  466. segmented_iterator(const segmented_iterator<SegmentedContainer, U>& other) :
  467. my_segcont(other.my_segcont),
  468. outer_iter(other.outer_iter),
  469. // can we assign a default-constructed iterator to inner if we're at the end?
  470. inner_iter(other.inner_iter)
  471. {}
  472. // assignment
  473. template<typename U>
  474. segmented_iterator& operator=( const segmented_iterator<SegmentedContainer, U>& other) {
  475. if(this != &other) {
  476. my_segcont = other.my_segcont;
  477. outer_iter = other.outer_iter;
  478. if(outer_iter != my_segcont->end()) inner_iter = other.inner_iter;
  479. }
  480. return *this;
  481. }
  482. // allow assignment of outer iterator to segmented iterator. Once it is
  483. // assigned, move forward until a non-empty inner container is found or
  484. // the end of the outer container is reached.
  485. segmented_iterator& operator=(const outer_iterator& new_outer_iter) {
  486. __TBB_ASSERT(my_segcont != NULL, NULL);
  487. // check that this iterator points to something inside the segmented container
  488. for(outer_iter = new_outer_iter ;outer_iter!=my_segcont->end(); ++outer_iter) {
  489. if( !outer_iter->empty() ) {
  490. inner_iter = outer_iter->begin();
  491. break;
  492. }
  493. }
  494. return *this;
  495. }
  496. // pre-increment
  497. segmented_iterator& operator++() {
  498. advance_me();
  499. return *this;
  500. }
  501. // post-increment
  502. segmented_iterator operator++(int) {
  503. segmented_iterator tmp = *this;
  504. operator++();
  505. return tmp;
  506. }
  507. bool operator==(const outer_iterator& other_outer) const {
  508. __TBB_ASSERT(my_segcont != NULL, NULL);
  509. return (outer_iter == other_outer &&
  510. (outer_iter == my_segcont->end() || inner_iter == outer_iter->begin()));
  511. }
  512. bool operator!=(const outer_iterator& other_outer) const {
  513. return !operator==(other_outer);
  514. }
  515. // (i)* RHS
  516. reference operator*() const {
  517. __TBB_ASSERT(my_segcont != NULL, NULL);
  518. __TBB_ASSERT(outer_iter != my_segcont->end(), "Dereferencing a pointer at end of container");
  519. __TBB_ASSERT(inner_iter != outer_iter->end(), NULL); // should never happen
  520. return *inner_iter;
  521. }
  522. // i->
  523. pointer operator->() const { return &operator*();}
  524. private:
  525. SegmentedContainer* my_segcont;
  526. outer_iterator outer_iter;
  527. inner_iterator inner_iter;
  528. void advance_me() {
  529. __TBB_ASSERT(my_segcont != NULL, NULL);
  530. __TBB_ASSERT(outer_iter != my_segcont->end(), NULL); // not true if there are no inner containers
  531. __TBB_ASSERT(inner_iter != outer_iter->end(), NULL); // not true if the inner containers are all empty.
  532. ++inner_iter;
  533. while(inner_iter == outer_iter->end() && ++outer_iter != my_segcont->end()) {
  534. inner_iter = outer_iter->begin();
  535. }
  536. }
  537. }; // segmented_iterator
  538. template<typename SegmentedContainer, typename T, typename U>
  539. bool operator==( const segmented_iterator<SegmentedContainer,T>& i,
  540. const segmented_iterator<SegmentedContainer,U>& j ) {
  541. if(i.my_segcont != j.my_segcont) return false;
  542. if(i.my_segcont == NULL) return true;
  543. if(i.outer_iter != j.outer_iter) return false;
  544. if(i.outer_iter == i.my_segcont->end()) return true;
  545. return i.inner_iter == j.inner_iter;
  546. }
  547. // !=
  548. template<typename SegmentedContainer, typename T, typename U>
  549. bool operator!=( const segmented_iterator<SegmentedContainer,T>& i,
  550. const segmented_iterator<SegmentedContainer,U>& j ) {
  551. return !(i==j);
  552. }
  553. template<typename T>
  554. struct construct_by_default: tbb::internal::no_assign {
  555. void construct(void*where) {new(where) T();} // C++ note: the () in T() ensure zero initialization.
  556. construct_by_default( int ) {}
  557. };
  558. template<typename T>
  559. struct construct_by_exemplar: tbb::internal::no_assign {
  560. const T exemplar;
  561. void construct(void*where) {new(where) T(exemplar);}
  562. construct_by_exemplar( const T& t ) : exemplar(t) {}
  563. #if __TBB_ETS_USE_CPP11
  564. construct_by_exemplar( T&& t ) : exemplar(std::move(t)) {}
  565. #endif
  566. };
  567. template<typename T, typename Finit>
  568. struct construct_by_finit: tbb::internal::no_assign {
  569. Finit f;
  570. void construct(void* where) {new(where) T(f());}
  571. construct_by_finit( const Finit& f_ ) : f(f_) {}
  572. #if __TBB_ETS_USE_CPP11
  573. construct_by_finit( Finit&& f_ ) : f(std::move(f_)) {}
  574. #endif
  575. };
  576. #if __TBB_ETS_USE_CPP11
  577. template<typename T, typename... P>
  578. struct construct_by_args: tbb::internal::no_assign {
  579. internal::stored_pack<P...> pack;
  580. void construct(void* where) {
  581. internal::call( [where](const typename strip<P>::type&... args ){
  582. new(where) T(args...);
  583. }, pack );
  584. }
  585. construct_by_args( P&& ... args ) : pack(std::forward<P>(args)...) {}
  586. };
  587. #endif
  588. // storage for initialization function pointer
  589. // TODO: consider removing the template parameter T here and in callback_leaf
  590. template<typename T>
  591. class callback_base {
  592. public:
  593. // Clone *this
  594. virtual callback_base* clone() const = 0;
  595. // Destruct and free *this
  596. virtual void destroy() = 0;
  597. // Need virtual destructor to satisfy GCC compiler warning
  598. virtual ~callback_base() { }
  599. // Construct T at where
  600. virtual void construct(void* where) = 0;
  601. };
  602. template <typename T, typename Constructor>
  603. class callback_leaf: public callback_base<T>, Constructor {
  604. #if __TBB_ETS_USE_CPP11
  605. template<typename... P> callback_leaf( P&& ... params ) : Constructor(std::forward<P>(params)...) {}
  606. #else
  607. template<typename X> callback_leaf( const X& x ) : Constructor(x) {}
  608. #endif
  609. // TODO: make the construction/destruction consistent (use allocator.construct/destroy)
  610. typedef typename tbb::tbb_allocator<callback_leaf> my_allocator_type;
  611. callback_base<T>* clone() const __TBB_override {
  612. return make(*this);
  613. }
  614. void destroy() __TBB_override {
  615. my_allocator_type().destroy(this);
  616. my_allocator_type().deallocate(this,1);
  617. }
  618. void construct(void* where) __TBB_override {
  619. Constructor::construct(where);
  620. }
  621. public:
  622. #if __TBB_ETS_USE_CPP11
  623. template<typename... P>
  624. static callback_base<T>* make( P&& ... params ) {
  625. void* where = my_allocator_type().allocate(1);
  626. return new(where) callback_leaf( std::forward<P>(params)... );
  627. }
  628. #else
  629. template<typename X>
  630. static callback_base<T>* make( const X& x ) {
  631. void* where = my_allocator_type().allocate(1);
  632. return new(where) callback_leaf(x);
  633. }
  634. #endif
  635. };
  636. //! Template for recording construction of objects in table
  637. /** All maintenance of the space will be done explicitly on push_back,
  638. and all thread local copies must be destroyed before the concurrent
  639. vector is deleted.
  640. The flag is_built is initialized to false. When the local is
  641. successfully-constructed, set the flag to true or call value_committed().
  642. If the constructor throws, the flag will be false.
  643. */
  644. template<typename U>
  645. struct ets_element {
  646. tbb::aligned_space<U> my_space;
  647. bool is_built;
  648. ets_element() { is_built = false; } // not currently-built
  649. U* value() { return my_space.begin(); }
  650. U* value_committed() { is_built = true; return my_space.begin(); }
  651. ~ets_element() {
  652. if(is_built) {
  653. my_space.begin()->~U();
  654. is_built = false;
  655. }
  656. }
  657. };
  658. // A predicate that can be used for a compile-time compatibility check of ETS instances
  659. // Ideally, it should have been declared inside the ETS class, but unfortunately
  660. // in that case VS2013 does not enable the variadic constructor.
  661. template<typename T, typename ETS> struct is_compatible_ets { static const bool value = false; };
  662. template<typename T, typename U, typename A, ets_key_usage_type C>
  663. struct is_compatible_ets< T, enumerable_thread_specific<U,A,C> > { static const bool value = internal::is_same_type<T,U>::value; };
  664. #if __TBB_ETS_USE_CPP11
  665. // A predicate that checks whether, for a variable 'foo' of type T, foo() is a valid expression
  666. template <typename T>
  667. class is_callable_no_args {
  668. private:
  669. typedef char yes[1];
  670. typedef char no [2];
  671. template<typename U> static yes& decide( decltype(declval<U>()())* );
  672. template<typename U> static no& decide(...);
  673. public:
  674. static const bool value = (sizeof(decide<T>(NULL)) == sizeof(yes));
  675. };
  676. #endif
  677. } // namespace internal
  678. //! @endcond
  679. //! The enumerable_thread_specific container
  680. /** enumerable_thread_specific has the following properties:
  681. - thread-local copies are lazily created, with default, exemplar or function initialization.
  682. - thread-local copies do not move (during lifetime, and excepting clear()) so the address of a copy is invariant.
  683. - the contained objects need not have operator=() defined if combine is not used.
  684. - enumerable_thread_specific containers may be copy-constructed or assigned.
  685. - thread-local copies can be managed by hash-table, or can be accessed via TLS storage for speed.
  686. - outside of parallel contexts, the contents of all thread-local copies are accessible by iterator or using combine or combine_each methods
  687. @par Segmented iterator
  688. When the thread-local objects are containers with input_iterators defined, a segmented iterator may
  689. be used to iterate over all the elements of all thread-local copies.
  690. @par combine and combine_each
  691. - Both methods are defined for enumerable_thread_specific.
  692. - combine() requires the type T have operator=() defined.
  693. - neither method modifies the contents of the object (though there is no guarantee that the applied methods do not modify the object.)
  694. - Both are evaluated in serial context (the methods are assumed to be non-benign.)
  695. @ingroup containers */
  696. template <typename T,
  697. typename Allocator=cache_aligned_allocator<T>,
  698. ets_key_usage_type ETS_key_type=ets_no_key >
  699. class enumerable_thread_specific: internal::ets_base<ETS_key_type> {
  700. template<typename U, typename A, ets_key_usage_type C> friend class enumerable_thread_specific;
  701. typedef internal::padded< internal::ets_element<T> > padded_element;
  702. //! A generic range, used to create range objects from the iterators
  703. template<typename I>
  704. class generic_range_type: public blocked_range<I> {
  705. public:
  706. typedef T value_type;
  707. typedef T& reference;
  708. typedef const T& const_reference;
  709. typedef I iterator;
  710. typedef ptrdiff_t difference_type;
  711. generic_range_type( I begin_, I end_, size_t grainsize_ = 1) : blocked_range<I>(begin_,end_,grainsize_) {}
  712. template<typename U>
  713. generic_range_type( const generic_range_type<U>& r) : blocked_range<I>(r.begin(),r.end(),r.grainsize()) {}
  714. generic_range_type( generic_range_type& r, split ) : blocked_range<I>(r,split()) {}
  715. };
  716. typedef typename Allocator::template rebind< padded_element >::other padded_allocator_type;
  717. typedef tbb::concurrent_vector< padded_element, padded_allocator_type > internal_collection_type;
  718. internal::callback_base<T> *my_construct_callback;
  719. internal_collection_type my_locals;
  720. // TODO: consider unifying the callback mechanism for all create_local* methods below
  721. // (likely non-compatible and requires interface version increase)
  722. void* create_local() __TBB_override {
  723. padded_element& lref = *my_locals.grow_by(1);
  724. my_construct_callback->construct(lref.value());
  725. return lref.value_committed();
  726. }
  727. static void* create_local_by_copy( internal::ets_base<ETS_key_type>& base, void* p ) {
  728. enumerable_thread_specific& ets = static_cast<enumerable_thread_specific&>(base);
  729. padded_element& lref = *ets.my_locals.grow_by(1);
  730. new(lref.value()) T(*static_cast<T*>(p));
  731. return lref.value_committed();
  732. }
  733. #if __TBB_ETS_USE_CPP11
  734. static void* create_local_by_move( internal::ets_base<ETS_key_type>& base, void* p ) {
  735. enumerable_thread_specific& ets = static_cast<enumerable_thread_specific&>(base);
  736. padded_element& lref = *ets.my_locals.grow_by(1);
  737. new(lref.value()) T(std::move(*static_cast<T*>(p)));
  738. return lref.value_committed();
  739. }
  740. #endif
  741. typedef typename Allocator::template rebind< uintptr_t >::other array_allocator_type;
  742. // _size is in bytes
  743. void* create_array(size_t _size) __TBB_override {
  744. size_t nelements = (_size + sizeof(uintptr_t) -1) / sizeof(uintptr_t);
  745. return array_allocator_type().allocate(nelements);
  746. }
  747. void free_array( void* _ptr, size_t _size) __TBB_override {
  748. size_t nelements = (_size + sizeof(uintptr_t) -1) / sizeof(uintptr_t);
  749. array_allocator_type().deallocate( reinterpret_cast<uintptr_t *>(_ptr),nelements);
  750. }
  751. public:
  752. //! Basic types
  753. typedef Allocator allocator_type;
  754. typedef T value_type;
  755. typedef T& reference;
  756. typedef const T& const_reference;
  757. typedef T* pointer;
  758. typedef const T* const_pointer;
  759. typedef typename internal_collection_type::size_type size_type;
  760. typedef typename internal_collection_type::difference_type difference_type;
  761. // Iterator types
  762. typedef typename internal::enumerable_thread_specific_iterator< internal_collection_type, value_type > iterator;
  763. typedef typename internal::enumerable_thread_specific_iterator< internal_collection_type, const value_type > const_iterator;
  764. // Parallel range types
  765. typedef generic_range_type< iterator > range_type;
  766. typedef generic_range_type< const_iterator > const_range_type;
  767. //! Default constructor. Each local instance of T is default constructed.
  768. enumerable_thread_specific() : my_construct_callback(
  769. internal::callback_leaf<T,internal::construct_by_default<T> >::make(/*dummy argument*/0)
  770. ){}
  771. //! Constructor with initializer functor. Each local instance of T is constructed by T(finit()).
  772. template <typename Finit
  773. #if __TBB_ETS_USE_CPP11
  774. , typename = typename internal::enable_if<internal::is_callable_no_args<typename internal::strip<Finit>::type>::value>::type
  775. #endif
  776. >
  777. explicit enumerable_thread_specific( Finit finit ) : my_construct_callback(
  778. internal::callback_leaf<T,internal::construct_by_finit<T,Finit> >::make( tbb::internal::move(finit) )
  779. ){}
  780. //! Constructor with exemplar. Each local instance of T is copy-constructed from the exemplar.
  781. explicit enumerable_thread_specific( const T& exemplar ) : my_construct_callback(
  782. internal::callback_leaf<T,internal::construct_by_exemplar<T> >::make( exemplar )
  783. ){}
  784. #if __TBB_ETS_USE_CPP11
  785. explicit enumerable_thread_specific( T&& exemplar ) : my_construct_callback(
  786. internal::callback_leaf<T,internal::construct_by_exemplar<T> >::make( std::move(exemplar) )
  787. ){}
  788. //! Variadic constructor with initializer arguments. Each local instance of T is constructed by T(args...)
  789. template <typename P1, typename... P,
  790. typename = typename internal::enable_if<!internal::is_callable_no_args<typename internal::strip<P1>::type>::value
  791. && !internal::is_compatible_ets<T, typename internal::strip<P1>::type>::value
  792. && !internal::is_same_type<T, typename internal::strip<P1>::type>::value
  793. >::type>
  794. enumerable_thread_specific( P1&& arg1, P&& ... args ) : my_construct_callback(
  795. internal::callback_leaf<T,internal::construct_by_args<T,P1,P...> >::make( std::forward<P1>(arg1), std::forward<P>(args)... )
  796. ){}
  797. #endif
  798. //! Destructor
  799. ~enumerable_thread_specific() {
  800. if(my_construct_callback) my_construct_callback->destroy();
  801. // Deallocate the hash table before overridden free_array() becomes inaccessible
  802. this->internal::ets_base<ETS_key_type>::table_clear();
  803. }
  804. //! returns reference to local, discarding exists
  805. reference local() {
  806. bool exists;
  807. return local(exists);
  808. }
  809. //! Returns reference to calling thread's local copy, creating one if necessary
  810. reference local(bool& exists) {
  811. void* ptr = this->table_lookup(exists);
  812. return *(T*)ptr;
  813. }
  814. //! Get the number of local copies
  815. size_type size() const { return my_locals.size(); }
  816. //! true if there have been no local copies created
  817. bool empty() const { return my_locals.empty(); }
  818. //! begin iterator
  819. iterator begin() { return iterator( my_locals, 0 ); }
  820. //! end iterator
  821. iterator end() { return iterator(my_locals, my_locals.size() ); }
  822. //! begin const iterator
  823. const_iterator begin() const { return const_iterator(my_locals, 0); }
  824. //! end const iterator
  825. const_iterator end() const { return const_iterator(my_locals, my_locals.size()); }
  826. //! Get range for parallel algorithms
  827. range_type range( size_t grainsize=1 ) { return range_type( begin(), end(), grainsize ); }
  828. //! Get const range for parallel algorithms
  829. const_range_type range( size_t grainsize=1 ) const { return const_range_type( begin(), end(), grainsize ); }
  830. //! Destroys local copies
  831. void clear() {
  832. my_locals.clear();
  833. this->table_clear();
  834. // callback is not destroyed
  835. }
  836. private:
  837. template<typename A2, ets_key_usage_type C2>
  838. void internal_copy(const enumerable_thread_specific<T, A2, C2>& other) {
  839. #if __TBB_ETS_USE_CPP11 && TBB_USE_ASSERT
  840. // this tests is_compatible_ets
  841. __TBB_STATIC_ASSERT( (internal::is_compatible_ets<T, typename internal::strip<decltype(other)>::type>::value), "is_compatible_ets fails" );
  842. #endif
  843. // Initialize my_construct_callback first, so that it is valid even if rest of this routine throws an exception.
  844. my_construct_callback = other.my_construct_callback->clone();
  845. __TBB_ASSERT(my_locals.size()==0,NULL);
  846. my_locals.reserve(other.size());
  847. this->table_elementwise_copy( other, create_local_by_copy );
  848. }
  849. void internal_swap(enumerable_thread_specific& other) {
  850. using std::swap;
  851. __TBB_ASSERT( this!=&other, NULL );
  852. swap(my_construct_callback, other.my_construct_callback);
  853. // concurrent_vector::swap() preserves storage space,
  854. // so addresses to the vector kept in ETS hash table remain valid.
  855. swap(my_locals, other.my_locals);
  856. this->internal::ets_base<ETS_key_type>::table_swap(other);
  857. }
  858. #if __TBB_ETS_USE_CPP11
  859. template<typename A2, ets_key_usage_type C2>
  860. void internal_move(enumerable_thread_specific<T, A2, C2>&& other) {
  861. #if TBB_USE_ASSERT
  862. // this tests is_compatible_ets
  863. __TBB_STATIC_ASSERT( (internal::is_compatible_ets<T, typename internal::strip<decltype(other)>::type>::value), "is_compatible_ets fails" );
  864. #endif
  865. my_construct_callback = other.my_construct_callback;
  866. other.my_construct_callback = NULL;
  867. __TBB_ASSERT(my_locals.size()==0,NULL);
  868. my_locals.reserve(other.size());
  869. this->table_elementwise_copy( other, create_local_by_move );
  870. }
  871. #endif
  872. public:
  873. enumerable_thread_specific( const enumerable_thread_specific& other )
  874. : internal::ets_base<ETS_key_type>() /* prevents GCC warnings with -Wextra */
  875. {
  876. internal_copy(other);
  877. }
  878. template<typename Alloc, ets_key_usage_type Cachetype>
  879. enumerable_thread_specific( const enumerable_thread_specific<T, Alloc, Cachetype>& other )
  880. {
  881. internal_copy(other);
  882. }
  883. #if __TBB_ETS_USE_CPP11
  884. enumerable_thread_specific( enumerable_thread_specific&& other ) : my_construct_callback()
  885. {
  886. internal_swap(other);
  887. }
  888. template<typename Alloc, ets_key_usage_type Cachetype>
  889. enumerable_thread_specific( enumerable_thread_specific<T, Alloc, Cachetype>&& other ) : my_construct_callback()
  890. {
  891. internal_move(std::move(other));
  892. }
  893. #endif
  894. enumerable_thread_specific& operator=( const enumerable_thread_specific& other )
  895. {
  896. if( this != &other ) {
  897. this->clear();
  898. my_construct_callback->destroy();
  899. internal_copy( other );
  900. }
  901. return *this;
  902. }
  903. template<typename Alloc, ets_key_usage_type Cachetype>
  904. enumerable_thread_specific& operator=( const enumerable_thread_specific<T, Alloc, Cachetype>& other )
  905. {
  906. __TBB_ASSERT( static_cast<void*>(this)!=static_cast<const void*>(&other), NULL ); // Objects of different types
  907. this->clear();
  908. my_construct_callback->destroy();
  909. internal_copy(other);
  910. return *this;
  911. }
  912. #if __TBB_ETS_USE_CPP11
  913. enumerable_thread_specific& operator=( enumerable_thread_specific&& other )
  914. {
  915. if( this != &other )
  916. internal_swap(other);
  917. return *this;
  918. }
  919. template<typename Alloc, ets_key_usage_type Cachetype>
  920. enumerable_thread_specific& operator=( enumerable_thread_specific<T, Alloc, Cachetype>&& other )
  921. {
  922. __TBB_ASSERT( static_cast<void*>(this)!=static_cast<const void*>(&other), NULL ); // Objects of different types
  923. this->clear();
  924. my_construct_callback->destroy();
  925. internal_move(std::move(other));
  926. return *this;
  927. }
  928. #endif
  929. // combine_func_t has signature T(T,T) or T(const T&, const T&)
  930. template <typename combine_func_t>
  931. T combine(combine_func_t f_combine) {
  932. if(begin() == end()) {
  933. internal::ets_element<T> location;
  934. my_construct_callback->construct(location.value());
  935. return *location.value_committed();
  936. }
  937. const_iterator ci = begin();
  938. T my_result = *ci;
  939. while(++ci != end())
  940. my_result = f_combine( my_result, *ci );
  941. return my_result;
  942. }
  943. // combine_func_t takes T by value or by [const] reference, and returns nothing
  944. template <typename combine_func_t>
  945. void combine_each(combine_func_t f_combine) {
  946. for(iterator ci = begin(); ci != end(); ++ci) {
  947. f_combine( *ci );
  948. }
  949. }
  950. }; // enumerable_thread_specific
  951. template< typename Container >
  952. class flattened2d {
  953. // This intermediate typedef is to address issues with VC7.1 compilers
  954. typedef typename Container::value_type conval_type;
  955. public:
  956. //! Basic types
  957. typedef typename conval_type::size_type size_type;
  958. typedef typename conval_type::difference_type difference_type;
  959. typedef typename conval_type::allocator_type allocator_type;
  960. typedef typename conval_type::value_type value_type;
  961. typedef typename conval_type::reference reference;
  962. typedef typename conval_type::const_reference const_reference;
  963. typedef typename conval_type::pointer pointer;
  964. typedef typename conval_type::const_pointer const_pointer;
  965. typedef typename internal::segmented_iterator<Container, value_type> iterator;
  966. typedef typename internal::segmented_iterator<Container, const value_type> const_iterator;
  967. flattened2d( const Container &c, typename Container::const_iterator b, typename Container::const_iterator e ) :
  968. my_container(const_cast<Container*>(&c)), my_begin(b), my_end(e) { }
  969. explicit flattened2d( const Container &c ) :
  970. my_container(const_cast<Container*>(&c)), my_begin(c.begin()), my_end(c.end()) { }
  971. iterator begin() { return iterator(*my_container) = my_begin; }
  972. iterator end() { return iterator(*my_container) = my_end; }
  973. const_iterator begin() const { return const_iterator(*my_container) = my_begin; }
  974. const_iterator end() const { return const_iterator(*my_container) = my_end; }
  975. size_type size() const {
  976. size_type tot_size = 0;
  977. for(typename Container::const_iterator i = my_begin; i != my_end; ++i) {
  978. tot_size += i->size();
  979. }
  980. return tot_size;
  981. }
  982. private:
  983. Container *my_container;
  984. typename Container::const_iterator my_begin;
  985. typename Container::const_iterator my_end;
  986. };
  987. template <typename Container>
  988. flattened2d<Container> flatten2d(const Container &c, const typename Container::const_iterator b, const typename Container::const_iterator e) {
  989. return flattened2d<Container>(c, b, e);
  990. }
  991. template <typename Container>
  992. flattened2d<Container> flatten2d(const Container &c) {
  993. return flattened2d<Container>(c);
  994. }
  995. } // interface6
  996. namespace internal {
  997. using interface6::internal::segmented_iterator;
  998. }
  999. using interface6::enumerable_thread_specific;
  1000. using interface6::flattened2d;
  1001. using interface6::flatten2d;
  1002. } // namespace tbb
  1003. #include "internal/_warning_suppress_disable_notice.h"
  1004. #undef __TBB_enumerable_thread_specific_H_include_area
  1005. #endif