concurrent_vector.h 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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_concurrent_vector_H
  14. #define __TBB_concurrent_vector_H
  15. #define __TBB_concurrent_vector_H_include_area
  16. #include "internal/_warning_suppress_enable_notice.h"
  17. #include "tbb_stddef.h"
  18. #include "tbb_exception.h"
  19. #include "atomic.h"
  20. #include "cache_aligned_allocator.h"
  21. #include "blocked_range.h"
  22. #include "tbb_machine.h"
  23. #include "tbb_profiling.h"
  24. #include <new>
  25. #include <cstring> // for memset()
  26. #include __TBB_STD_SWAP_HEADER
  27. #include <algorithm>
  28. #include <iterator>
  29. #include "internal/_allocator_traits.h"
  30. #if _MSC_VER==1500 && !__INTEL_COMPILER
  31. // VS2008/VC9 seems to have an issue; limits pull in math.h
  32. #pragma warning( push )
  33. #pragma warning( disable: 4985 )
  34. #endif
  35. #include <limits> /* std::numeric_limits */
  36. #if _MSC_VER==1500 && !__INTEL_COMPILER
  37. #pragma warning( pop )
  38. #endif
  39. #if __TBB_INITIALIZER_LISTS_PRESENT
  40. #include <initializer_list>
  41. #endif
  42. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  43. // Workaround for overzealous compiler warnings in /Wp64 mode
  44. #pragma warning (push)
  45. #if defined(_Wp64)
  46. #pragma warning (disable: 4267)
  47. #endif
  48. #pragma warning (disable: 4127) //warning C4127: conditional expression is constant
  49. #endif
  50. namespace tbb {
  51. template<typename T, class A = cache_aligned_allocator<T> >
  52. class concurrent_vector;
  53. //! @cond INTERNAL
  54. namespace internal {
  55. template<typename Container, typename Value>
  56. class vector_iterator;
  57. //! Bad allocation marker
  58. static void *const vector_allocation_error_flag = reinterpret_cast<void*>(size_t(63));
  59. //! Exception helper function
  60. template<typename T>
  61. void handle_unconstructed_elements(T* array, size_t n_of_elements){
  62. std::memset( static_cast<void*>(array), 0, n_of_elements * sizeof( T ) );
  63. }
  64. //! Base class of concurrent vector implementation.
  65. /** @ingroup containers */
  66. class concurrent_vector_base_v3 {
  67. protected:
  68. // Basic types declarations
  69. typedef size_t segment_index_t;
  70. typedef size_t size_type;
  71. // Using enumerations due to Mac linking problems of static const variables
  72. enum {
  73. // Size constants
  74. default_initial_segments = 1, // 2 initial items
  75. //! Number of slots for segment pointers inside the class
  76. pointers_per_short_table = 3, // to fit into 8 words of entire structure
  77. pointers_per_long_table = sizeof(segment_index_t) * 8 // one segment per bit
  78. };
  79. struct segment_not_used {};
  80. struct segment_allocated {};
  81. struct segment_allocation_failed {};
  82. class segment_t;
  83. class segment_value_t {
  84. void* array;
  85. private:
  86. //TODO: More elegant way to grant access to selected functions _only_?
  87. friend class segment_t;
  88. explicit segment_value_t(void* an_array):array(an_array) {}
  89. public:
  90. friend bool operator==(segment_value_t const& lhs, segment_not_used ) { return lhs.array == 0;}
  91. friend bool operator==(segment_value_t const& lhs, segment_allocated) { return lhs.array > internal::vector_allocation_error_flag;}
  92. friend bool operator==(segment_value_t const& lhs, segment_allocation_failed) { return lhs.array == internal::vector_allocation_error_flag;}
  93. template<typename argument_type>
  94. friend bool operator!=(segment_value_t const& lhs, argument_type arg) { return ! (lhs == arg);}
  95. template<typename T>
  96. T* pointer() const { return static_cast<T*>(const_cast<void*>(array)); }
  97. };
  98. friend void enforce_segment_allocated(segment_value_t const& s, internal::exception_id exception = eid_bad_last_alloc){
  99. if(s != segment_allocated()){
  100. internal::throw_exception(exception);
  101. }
  102. }
  103. // Segment pointer.
  104. class segment_t {
  105. atomic<void*> array;
  106. public:
  107. segment_t(){ store<relaxed>(segment_not_used());}
  108. //Copy ctor and assignment operator are defined to ease using of stl algorithms.
  109. //These algorithms usually not a synchronization point, so, semantic is
  110. //intentionally relaxed here.
  111. segment_t(segment_t const& rhs ){ array.store<relaxed>(rhs.array.load<relaxed>());}
  112. void swap(segment_t & rhs ){
  113. tbb::internal::swap<relaxed>(array, rhs.array);
  114. }
  115. segment_t& operator=(segment_t const& rhs ){
  116. array.store<relaxed>(rhs.array.load<relaxed>());
  117. return *this;
  118. }
  119. template<memory_semantics M>
  120. segment_value_t load() const { return segment_value_t(array.load<M>());}
  121. template<memory_semantics M>
  122. void store(segment_not_used) {
  123. array.store<M>(0);
  124. }
  125. template<memory_semantics M>
  126. void store(segment_allocation_failed) {
  127. __TBB_ASSERT(load<relaxed>() != segment_allocated(),"transition from \"allocated\" to \"allocation failed\" state looks non-logical");
  128. array.store<M>(internal::vector_allocation_error_flag);
  129. }
  130. template<memory_semantics M>
  131. void store(void* allocated_segment_pointer) __TBB_NOEXCEPT(true) {
  132. __TBB_ASSERT(segment_value_t(allocated_segment_pointer) == segment_allocated(),
  133. "other overloads of store should be used for marking segment as not_used or allocation_failed" );
  134. array.store<M>(allocated_segment_pointer);
  135. }
  136. #if TBB_USE_ASSERT
  137. ~segment_t() {
  138. __TBB_ASSERT(load<relaxed>() != segment_allocated(), "should have been freed by clear" );
  139. }
  140. #endif /* TBB_USE_ASSERT */
  141. };
  142. friend void swap(segment_t & , segment_t & ) __TBB_NOEXCEPT(true);
  143. // Data fields
  144. //! allocator function pointer
  145. void* (*vector_allocator_ptr)(concurrent_vector_base_v3 &, size_t);
  146. //! count of segments in the first block
  147. atomic<size_type> my_first_block;
  148. //! Requested size of vector
  149. atomic<size_type> my_early_size;
  150. //! Pointer to the segments table
  151. atomic<segment_t*> my_segment;
  152. //! embedded storage of segment pointers
  153. segment_t my_storage[pointers_per_short_table];
  154. // Methods
  155. concurrent_vector_base_v3() {
  156. //Here the semantic is intentionally relaxed.
  157. //The reason this is next:
  158. //Object that is in middle of construction (i.e. its constructor is not yet finished)
  159. //cannot be used concurrently until the construction is finished.
  160. //Thus to flag other threads that construction is finished, some synchronization with
  161. //acquire-release semantic should be done by the (external) code that uses the vector.
  162. //So, no need to do the synchronization inside the vector.
  163. my_early_size.store<relaxed>(0);
  164. my_first_block.store<relaxed>(0); // here is not default_initial_segments
  165. my_segment.store<relaxed>(my_storage);
  166. }
  167. __TBB_EXPORTED_METHOD ~concurrent_vector_base_v3();
  168. //these helpers methods use the fact that segments are allocated so
  169. //that every segment size is a (increasing) power of 2.
  170. //with one exception 0 segment has size of 2 as well segment 1;
  171. //e.g. size of segment with index of 3 is 2^3=8;
  172. static segment_index_t segment_index_of( size_type index ) {
  173. return segment_index_t( __TBB_Log2( index|1 ) );
  174. }
  175. static segment_index_t segment_base( segment_index_t k ) {
  176. return (segment_index_t(1)<<k & ~segment_index_t(1));
  177. }
  178. static inline segment_index_t segment_base_index_of( segment_index_t &index ) {
  179. segment_index_t k = segment_index_of( index );
  180. index -= segment_base(k);
  181. return k;
  182. }
  183. static size_type segment_size( segment_index_t k ) {
  184. return segment_index_t(1)<<k; // fake value for k==0
  185. }
  186. static bool is_first_element_in_segment(size_type element_index){
  187. //check if element_index is a power of 2 that is at least 2.
  188. //The idea is to detect if the iterator crosses a segment boundary,
  189. //and 2 is the minimal index for which it's true
  190. __TBB_ASSERT(element_index, "there should be no need to call "
  191. "is_first_element_in_segment for 0th element" );
  192. return is_power_of_two_at_least( element_index, 2 );
  193. }
  194. //! An operation on an n-element array starting at begin.
  195. typedef void (__TBB_EXPORTED_FUNC *internal_array_op1)(void* begin, size_type n );
  196. //! An operation on n-element destination array and n-element source array.
  197. typedef void (__TBB_EXPORTED_FUNC *internal_array_op2)(void* dst, const void* src, size_type n );
  198. //! Internal structure for compact()
  199. struct internal_segments_table {
  200. segment_index_t first_block;
  201. segment_t table[pointers_per_long_table];
  202. };
  203. void __TBB_EXPORTED_METHOD internal_reserve( size_type n, size_type element_size, size_type max_size );
  204. size_type __TBB_EXPORTED_METHOD internal_capacity() const;
  205. void internal_grow( size_type start, size_type finish, size_type element_size, internal_array_op2 init, const void *src );
  206. size_type __TBB_EXPORTED_METHOD internal_grow_by( size_type delta, size_type element_size, internal_array_op2 init, const void *src );
  207. void* __TBB_EXPORTED_METHOD internal_push_back( size_type element_size, size_type& index );
  208. segment_index_t __TBB_EXPORTED_METHOD internal_clear( internal_array_op1 destroy );
  209. void* __TBB_EXPORTED_METHOD internal_compact( size_type element_size, void *table, internal_array_op1 destroy, internal_array_op2 copy );
  210. void __TBB_EXPORTED_METHOD internal_copy( const concurrent_vector_base_v3& src, size_type element_size, internal_array_op2 copy );
  211. void __TBB_EXPORTED_METHOD internal_assign( const concurrent_vector_base_v3& src, size_type element_size,
  212. internal_array_op1 destroy, internal_array_op2 assign, internal_array_op2 copy );
  213. //! Obsolete
  214. void __TBB_EXPORTED_METHOD internal_throw_exception(size_type) const;
  215. void __TBB_EXPORTED_METHOD internal_swap(concurrent_vector_base_v3& v);
  216. void __TBB_EXPORTED_METHOD internal_resize( size_type n, size_type element_size, size_type max_size, const void *src,
  217. internal_array_op1 destroy, internal_array_op2 init );
  218. size_type __TBB_EXPORTED_METHOD internal_grow_to_at_least_with_result( size_type new_size, size_type element_size, internal_array_op2 init, const void *src );
  219. //! Deprecated entry point for backwards compatibility to TBB 2.1.
  220. void __TBB_EXPORTED_METHOD internal_grow_to_at_least( size_type new_size, size_type element_size, internal_array_op2 init, const void *src );
  221. private:
  222. //! Private functionality
  223. class helper;
  224. friend class helper;
  225. template<typename Container, typename Value>
  226. friend class vector_iterator;
  227. };
  228. inline void swap(concurrent_vector_base_v3::segment_t & lhs, concurrent_vector_base_v3::segment_t & rhs) __TBB_NOEXCEPT(true) {
  229. lhs.swap(rhs);
  230. }
  231. typedef concurrent_vector_base_v3 concurrent_vector_base;
  232. //! Meets requirements of a forward iterator for STL and a Value for a blocked_range.*/
  233. /** Value is either the T or const T type of the container.
  234. @ingroup containers */
  235. template<typename Container, typename Value>
  236. class vector_iterator
  237. {
  238. //! concurrent_vector over which we are iterating.
  239. Container* my_vector;
  240. //! Index into the vector
  241. size_t my_index;
  242. //! Caches my_vector-&gt;internal_subscript(my_index)
  243. /** NULL if cached value is not available */
  244. mutable Value* my_item;
  245. template<typename C, typename T>
  246. friend vector_iterator<C,T> operator+( ptrdiff_t offset, const vector_iterator<C,T>& v );
  247. template<typename C, typename T, typename U>
  248. friend bool operator==( const vector_iterator<C,T>& i, const vector_iterator<C,U>& j );
  249. template<typename C, typename T, typename U>
  250. friend bool operator<( const vector_iterator<C,T>& i, const vector_iterator<C,U>& j );
  251. template<typename C, typename T, typename U>
  252. friend ptrdiff_t operator-( const vector_iterator<C,T>& i, const vector_iterator<C,U>& j );
  253. template<typename C, typename U>
  254. friend class internal::vector_iterator;
  255. #if !__TBB_TEMPLATE_FRIENDS_BROKEN
  256. template<typename T, class A>
  257. friend class tbb::concurrent_vector;
  258. #else
  259. public:
  260. #endif
  261. vector_iterator( const Container& vector, size_t index, void *ptr = 0 ) :
  262. my_vector(const_cast<Container*>(&vector)),
  263. my_index(index),
  264. my_item(static_cast<Value*>(ptr))
  265. {}
  266. public:
  267. //! Default constructor
  268. vector_iterator() : my_vector(NULL), my_index(~size_t(0)), my_item(NULL) {}
  269. vector_iterator( const vector_iterator<Container,typename Container::value_type>& other ) :
  270. my_vector(other.my_vector),
  271. my_index(other.my_index),
  272. my_item(other.my_item)
  273. {}
  274. vector_iterator& operator=( const vector_iterator<Container,typename Container::value_type>& other )
  275. {
  276. my_vector=other.my_vector;
  277. my_index=other.my_index;
  278. my_item=other.my_item;
  279. return *this;
  280. }
  281. vector_iterator operator+( ptrdiff_t offset ) const {
  282. return vector_iterator( *my_vector, my_index+offset );
  283. }
  284. vector_iterator &operator+=( ptrdiff_t offset ) {
  285. my_index+=offset;
  286. my_item = NULL;
  287. return *this;
  288. }
  289. vector_iterator operator-( ptrdiff_t offset ) const {
  290. return vector_iterator( *my_vector, my_index-offset );
  291. }
  292. vector_iterator &operator-=( ptrdiff_t offset ) {
  293. my_index-=offset;
  294. my_item = NULL;
  295. return *this;
  296. }
  297. Value& operator*() const {
  298. Value* item = my_item;
  299. if( !item ) {
  300. item = my_item = &my_vector->internal_subscript(my_index);
  301. }
  302. __TBB_ASSERT( item==&my_vector->internal_subscript(my_index), "corrupt cache" );
  303. return *item;
  304. }
  305. Value& operator[]( ptrdiff_t k ) const {
  306. return my_vector->internal_subscript(my_index+k);
  307. }
  308. Value* operator->() const {return &operator*();}
  309. //! Pre increment
  310. vector_iterator& operator++() {
  311. size_t element_index = ++my_index;
  312. if( my_item ) {
  313. //TODO: consider using of knowledge about "first_block optimization" here as well?
  314. if( concurrent_vector_base::is_first_element_in_segment(element_index)) {
  315. //if the iterator crosses a segment boundary, the pointer become invalid
  316. //as possibly next segment is in another memory location
  317. my_item= NULL;
  318. } else {
  319. ++my_item;
  320. }
  321. }
  322. return *this;
  323. }
  324. //! Pre decrement
  325. vector_iterator& operator--() {
  326. __TBB_ASSERT( my_index>0, "operator--() applied to iterator already at beginning of concurrent_vector" );
  327. size_t element_index = my_index--;
  328. if( my_item ) {
  329. if(concurrent_vector_base::is_first_element_in_segment(element_index)) {
  330. //if the iterator crosses a segment boundary, the pointer become invalid
  331. //as possibly next segment is in another memory location
  332. my_item= NULL;
  333. } else {
  334. --my_item;
  335. }
  336. }
  337. return *this;
  338. }
  339. //! Post increment
  340. vector_iterator operator++(int) {
  341. vector_iterator result = *this;
  342. operator++();
  343. return result;
  344. }
  345. //! Post decrement
  346. vector_iterator operator--(int) {
  347. vector_iterator result = *this;
  348. operator--();
  349. return result;
  350. }
  351. // STL support
  352. typedef ptrdiff_t difference_type;
  353. typedef Value value_type;
  354. typedef Value* pointer;
  355. typedef Value& reference;
  356. typedef std::random_access_iterator_tag iterator_category;
  357. };
  358. template<typename Container, typename T>
  359. vector_iterator<Container,T> operator+( ptrdiff_t offset, const vector_iterator<Container,T>& v ) {
  360. return vector_iterator<Container,T>( *v.my_vector, v.my_index+offset );
  361. }
  362. template<typename Container, typename T, typename U>
  363. bool operator==( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  364. return i.my_index==j.my_index && i.my_vector == j.my_vector;
  365. }
  366. template<typename Container, typename T, typename U>
  367. bool operator!=( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  368. return !(i==j);
  369. }
  370. template<typename Container, typename T, typename U>
  371. bool operator<( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  372. return i.my_index<j.my_index;
  373. }
  374. template<typename Container, typename T, typename U>
  375. bool operator>( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  376. return j<i;
  377. }
  378. template<typename Container, typename T, typename U>
  379. bool operator>=( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  380. return !(i<j);
  381. }
  382. template<typename Container, typename T, typename U>
  383. bool operator<=( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  384. return !(j<i);
  385. }
  386. template<typename Container, typename T, typename U>
  387. ptrdiff_t operator-( const vector_iterator<Container,T>& i, const vector_iterator<Container,U>& j ) {
  388. return ptrdiff_t(i.my_index)-ptrdiff_t(j.my_index);
  389. }
  390. template<typename T, class A>
  391. class allocator_base {
  392. public:
  393. typedef typename tbb::internal::allocator_rebind<A, T>::type allocator_type;
  394. allocator_type my_allocator;
  395. allocator_base(const allocator_type &a = allocator_type() ) : my_allocator(a) {}
  396. };
  397. } // namespace internal
  398. //! @endcond
  399. //! Concurrent vector container
  400. /** concurrent_vector is a container having the following main properties:
  401. - It provides random indexed access to its elements. The index of the first element is 0.
  402. - It ensures safe concurrent growing its size (different threads can safely append new elements).
  403. - Adding new elements does not invalidate existing iterators and does not change indices of existing items.
  404. @par Compatibility
  405. The class meets all Container Requirements and Reversible Container Requirements from
  406. C++ Standard (See ISO/IEC 14882:2003(E), clause 23.1). But it doesn't meet
  407. Sequence Requirements due to absence of insert() and erase() methods.
  408. @par Exception Safety
  409. Methods working with memory allocation and/or new elements construction can throw an
  410. exception if allocator fails to allocate memory or element's default constructor throws one.
  411. Concurrent vector's element of type T must conform to the following requirements:
  412. - Throwing an exception is forbidden for destructor of T.
  413. - Default constructor of T must not throw an exception OR its non-virtual destructor must safely work when its object memory is zero-initialized.
  414. .
  415. Otherwise, the program's behavior is undefined.
  416. @par
  417. If an exception happens inside growth or assignment operation, an instance of the vector becomes invalid unless it is stated otherwise in the method documentation.
  418. Invalid state means:
  419. - There are no guarantees that all items were initialized by a constructor. The rest of items is zero-filled, including item where exception happens.
  420. - An invalid vector instance cannot be repaired; it is unable to grow anymore.
  421. - Size and capacity reported by the vector are incorrect, and calculated as if the failed operation were successful.
  422. - Attempt to access not allocated elements using operator[] or iterators results in access violation or segmentation fault exception, and in case of using at() method a C++ exception is thrown.
  423. .
  424. If a concurrent grow operation successfully completes, all the elements it has added to the vector will remain valid and accessible even if one of subsequent grow operations fails.
  425. @par Fragmentation
  426. Unlike an STL vector, a concurrent_vector does not move existing elements if it needs
  427. to allocate more memory. The container is divided into a series of contiguous arrays of
  428. elements. The first reservation, growth, or assignment operation determines the size of
  429. the first array. Using small number of elements as initial size incurs fragmentation that
  430. may increase element access time. Internal layout can be optimized by method compact() that
  431. merges several smaller arrays into one solid.
  432. @par Changes since TBB 2.1
  433. - Fixed guarantees of concurrent_vector::size() and grow_to_at_least() methods to assure elements are allocated.
  434. - Methods end()/rbegin()/back() are partly thread-safe since they use size() to get the end of vector
  435. - Added resize() methods (not thread-safe)
  436. - Added cbegin/cend/crbegin/crend methods
  437. - Changed return type of methods grow* and push_back to iterator
  438. @par Changes since TBB 2.0
  439. - Implemented exception-safety guarantees
  440. - Added template argument for allocator
  441. - Added allocator argument in constructors
  442. - Faster index calculation
  443. - First growth call specifies a number of segments to be merged in the first allocation.
  444. - Fixed memory blow up for swarm of vector's instances of small size
  445. - Added grow_by(size_type n, const_reference t) growth using copying constructor to init new items.
  446. - Added STL-like constructors.
  447. - Added operators ==, < and derivatives
  448. - Added at() method, approved for using after an exception was thrown inside the vector
  449. - Added get_allocator() method.
  450. - Added assign() methods
  451. - Added compact() method to defragment first segments
  452. - Added swap() method
  453. - range() defaults on grainsize = 1 supporting auto grainsize algorithms.
  454. @ingroup containers */
  455. template<typename T, class A>
  456. class concurrent_vector: protected internal::allocator_base<T, A>,
  457. private internal::concurrent_vector_base {
  458. private:
  459. template<typename I>
  460. class generic_range_type: public blocked_range<I> {
  461. public:
  462. typedef T value_type;
  463. typedef T& reference;
  464. typedef const T& const_reference;
  465. typedef I iterator;
  466. typedef ptrdiff_t difference_type;
  467. generic_range_type( I begin_, I end_, size_t grainsize_ = 1) : blocked_range<I>(begin_,end_,grainsize_) {}
  468. template<typename U>
  469. generic_range_type( const generic_range_type<U>& r) : blocked_range<I>(r.begin(),r.end(),r.grainsize()) {}
  470. generic_range_type( generic_range_type& r, split ) : blocked_range<I>(r,split()) {}
  471. };
  472. template<typename C, typename U>
  473. friend class internal::vector_iterator;
  474. public:
  475. //------------------------------------------------------------------------
  476. // STL compatible types
  477. //------------------------------------------------------------------------
  478. typedef internal::concurrent_vector_base_v3::size_type size_type;
  479. typedef typename internal::allocator_base<T, A>::allocator_type allocator_type;
  480. typedef T value_type;
  481. typedef ptrdiff_t difference_type;
  482. typedef T& reference;
  483. typedef const T& const_reference;
  484. typedef T *pointer;
  485. typedef const T *const_pointer;
  486. typedef internal::vector_iterator<concurrent_vector,T> iterator;
  487. typedef internal::vector_iterator<concurrent_vector,const T> const_iterator;
  488. #if !defined(_MSC_VER) || _CPPLIB_VER>=300
  489. // Assume ISO standard definition of std::reverse_iterator
  490. typedef std::reverse_iterator<iterator> reverse_iterator;
  491. typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
  492. #else
  493. // Use non-standard std::reverse_iterator
  494. typedef std::reverse_iterator<iterator,T,T&,T*> reverse_iterator;
  495. typedef std::reverse_iterator<const_iterator,T,const T&,const T*> const_reverse_iterator;
  496. #endif /* defined(_MSC_VER) && (_MSC_VER<1300) */
  497. //------------------------------------------------------------------------
  498. // Parallel algorithm support
  499. //------------------------------------------------------------------------
  500. typedef generic_range_type<iterator> range_type;
  501. typedef generic_range_type<const_iterator> const_range_type;
  502. //------------------------------------------------------------------------
  503. // STL compatible constructors & destructors
  504. //------------------------------------------------------------------------
  505. //! Construct empty vector.
  506. explicit concurrent_vector(const allocator_type &a = allocator_type())
  507. : internal::allocator_base<T, A>(a), internal::concurrent_vector_base()
  508. {
  509. vector_allocator_ptr = &internal_allocator;
  510. }
  511. //Constructors are not required to have synchronization
  512. //(for more details see comment in the concurrent_vector_base constructor).
  513. #if __TBB_INITIALIZER_LISTS_PRESENT
  514. //! Constructor from initializer_list
  515. concurrent_vector(std::initializer_list<T> init_list, const allocator_type &a = allocator_type())
  516. : internal::allocator_base<T, A>(a), internal::concurrent_vector_base()
  517. {
  518. vector_allocator_ptr = &internal_allocator;
  519. __TBB_TRY {
  520. internal_assign_iterators(init_list.begin(), init_list.end());
  521. } __TBB_CATCH(...) {
  522. segment_t *table = my_segment.load<relaxed>();;
  523. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>());
  524. __TBB_RETHROW();
  525. }
  526. }
  527. #endif //# __TBB_INITIALIZER_LISTS_PRESENT
  528. //! Copying constructor
  529. concurrent_vector( const concurrent_vector& vector, const allocator_type& a = allocator_type() )
  530. : internal::allocator_base<T, A>(a), internal::concurrent_vector_base()
  531. {
  532. vector_allocator_ptr = &internal_allocator;
  533. __TBB_TRY {
  534. internal_copy(vector, sizeof(T), &copy_array);
  535. } __TBB_CATCH(...) {
  536. segment_t *table = my_segment.load<relaxed>();
  537. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>());
  538. __TBB_RETHROW();
  539. }
  540. }
  541. #if __TBB_CPP11_RVALUE_REF_PRESENT
  542. //! Move constructor
  543. //TODO add __TBB_NOEXCEPT(true) and static_assert(std::has_nothrow_move_constructor<A>::value)
  544. concurrent_vector( concurrent_vector&& source)
  545. : internal::allocator_base<T, A>(std::move(source)), internal::concurrent_vector_base()
  546. {
  547. vector_allocator_ptr = &internal_allocator;
  548. concurrent_vector_base_v3::internal_swap(source);
  549. }
  550. concurrent_vector( concurrent_vector&& source, const allocator_type& a)
  551. : internal::allocator_base<T, A>(a), internal::concurrent_vector_base()
  552. {
  553. vector_allocator_ptr = &internal_allocator;
  554. //C++ standard requires instances of an allocator being compared for equality,
  555. //which means that memory allocated by one instance is possible to deallocate with the other one.
  556. if (a == source.my_allocator) {
  557. concurrent_vector_base_v3::internal_swap(source);
  558. } else {
  559. __TBB_TRY {
  560. internal_copy(source, sizeof(T), &move_array);
  561. } __TBB_CATCH(...) {
  562. segment_t *table = my_segment.load<relaxed>();
  563. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>());
  564. __TBB_RETHROW();
  565. }
  566. }
  567. }
  568. #endif
  569. //! Copying constructor for vector with different allocator type
  570. template<class M>
  571. __TBB_DEPRECATED concurrent_vector( const concurrent_vector<T, M>& vector, const allocator_type& a = allocator_type() )
  572. : internal::allocator_base<T, A>(a), internal::concurrent_vector_base()
  573. {
  574. vector_allocator_ptr = &internal_allocator;
  575. __TBB_TRY {
  576. internal_copy(vector.internal_vector_base(), sizeof(T), &copy_array);
  577. } __TBB_CATCH(...) {
  578. segment_t *table = my_segment.load<relaxed>();
  579. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>() );
  580. __TBB_RETHROW();
  581. }
  582. }
  583. //! Construction with initial size specified by argument n
  584. explicit concurrent_vector(size_type n)
  585. {
  586. vector_allocator_ptr = &internal_allocator;
  587. __TBB_TRY {
  588. internal_resize( n, sizeof(T), max_size(), NULL, &destroy_array, &initialize_array );
  589. } __TBB_CATCH(...) {
  590. segment_t *table = my_segment.load<relaxed>();
  591. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>() );
  592. __TBB_RETHROW();
  593. }
  594. }
  595. //! Construction with initial size specified by argument n, initialization by copying of t, and given allocator instance
  596. concurrent_vector(size_type n, const_reference t, const allocator_type& a = allocator_type())
  597. : internal::allocator_base<T, A>(a)
  598. {
  599. vector_allocator_ptr = &internal_allocator;
  600. __TBB_TRY {
  601. internal_resize( n, sizeof(T), max_size(), static_cast<const void*>(&t), &destroy_array, &initialize_array_by );
  602. } __TBB_CATCH(...) {
  603. segment_t *table = my_segment.load<relaxed>();
  604. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>() );
  605. __TBB_RETHROW();
  606. }
  607. }
  608. //! Construction with copying iteration range and given allocator instance
  609. template<class I>
  610. concurrent_vector(I first, I last, const allocator_type &a = allocator_type())
  611. : internal::allocator_base<T, A>(a)
  612. {
  613. vector_allocator_ptr = &internal_allocator;
  614. __TBB_TRY {
  615. internal_assign_range(first, last, static_cast<is_integer_tag<std::numeric_limits<I>::is_integer> *>(0) );
  616. } __TBB_CATCH(...) {
  617. segment_t *table = my_segment.load<relaxed>();
  618. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>() );
  619. __TBB_RETHROW();
  620. }
  621. }
  622. //! Assignment
  623. concurrent_vector& operator=( const concurrent_vector& vector ) {
  624. if( this != &vector )
  625. internal_assign(vector, sizeof(T), &destroy_array, &assign_array, &copy_array);
  626. return *this;
  627. }
  628. #if __TBB_CPP11_RVALUE_REF_PRESENT
  629. //TODO: add __TBB_NOEXCEPT()
  630. //! Move assignment
  631. concurrent_vector& operator=( concurrent_vector&& other ) {
  632. __TBB_ASSERT(this != &other, "Move assignment to itself is prohibited ");
  633. typedef typename tbb::internal::allocator_traits<A>::propagate_on_container_move_assignment pocma_t;
  634. if(pocma_t::value || this->my_allocator == other.my_allocator) {
  635. concurrent_vector trash (std::move(*this));
  636. internal_swap(other);
  637. tbb::internal::allocator_move_assignment(this->my_allocator, other.my_allocator, pocma_t());
  638. } else {
  639. internal_assign(other, sizeof(T), &destroy_array, &move_assign_array, &move_array);
  640. }
  641. return *this;
  642. }
  643. #endif
  644. //TODO: add an template assignment operator? (i.e. with different element type)
  645. //! Assignment for vector with different allocator type
  646. template<class M>
  647. __TBB_DEPRECATED concurrent_vector& operator=( const concurrent_vector<T, M>& vector ) {
  648. if( static_cast<void*>( this ) != static_cast<const void*>( &vector ) )
  649. internal_assign(vector.internal_vector_base(),
  650. sizeof(T), &destroy_array, &assign_array, &copy_array);
  651. return *this;
  652. }
  653. #if __TBB_INITIALIZER_LISTS_PRESENT
  654. //! Assignment for initializer_list
  655. concurrent_vector& operator=( std::initializer_list<T> init_list ) {
  656. internal_clear(&destroy_array);
  657. internal_assign_iterators(init_list.begin(), init_list.end());
  658. return *this;
  659. }
  660. #endif //#if __TBB_INITIALIZER_LISTS_PRESENT
  661. //------------------------------------------------------------------------
  662. // Concurrent operations
  663. //------------------------------------------------------------------------
  664. //! Grow by "delta" elements.
  665. /** Returns iterator pointing to the first new element. */
  666. iterator grow_by( size_type delta ) {
  667. return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array, NULL ) : my_early_size.load());
  668. }
  669. //! Grow by "delta" elements using copying constructor.
  670. /** Returns iterator pointing to the first new element. */
  671. iterator grow_by( size_type delta, const_reference t ) {
  672. return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array_by, static_cast<const void*>(&t) ) : my_early_size.load());
  673. }
  674. /** Returns iterator pointing to the first new element. */
  675. template<typename I>
  676. iterator grow_by( I first, I last ) {
  677. typename std::iterator_traits<I>::difference_type delta = std::distance(first, last);
  678. __TBB_ASSERT( delta >= 0, NULL);
  679. return iterator(*this, delta ? internal_grow_by(delta, sizeof(T), &copy_range<I>, static_cast<const void*>(&first)) : my_early_size.load());
  680. }
  681. #if __TBB_INITIALIZER_LISTS_PRESENT
  682. /** Returns iterator pointing to the first new element. */
  683. iterator grow_by( std::initializer_list<T> init_list ) {
  684. return grow_by( init_list.begin(), init_list.end() );
  685. }
  686. #endif //#if __TBB_INITIALIZER_LISTS_PRESENT
  687. //! Append minimal sequence of elements such that size()>=n.
  688. /** The new elements are default constructed. Blocks until all elements in range [0..n) are allocated.
  689. May return while other elements are being constructed by other threads.
  690. Returns iterator that points to beginning of appended sequence.
  691. If no elements were appended, returns iterator pointing to nth element. */
  692. iterator grow_to_at_least( size_type n ) {
  693. size_type m=0;
  694. if( n ) {
  695. m = internal_grow_to_at_least_with_result( n, sizeof(T), &initialize_array, NULL );
  696. if( m>n ) m=n;
  697. }
  698. return iterator(*this, m);
  699. };
  700. /** Analogous to grow_to_at_least( size_type n ) with exception that the new
  701. elements are initialized by copying of t instead of default construction. */
  702. iterator grow_to_at_least( size_type n, const_reference t ) {
  703. size_type m=0;
  704. if( n ) {
  705. m = internal_grow_to_at_least_with_result( n, sizeof(T), &initialize_array_by, &t);
  706. if( m>n ) m=n;
  707. }
  708. return iterator(*this, m);
  709. };
  710. //! Push item
  711. /** Returns iterator pointing to the new element. */
  712. iterator push_back( const_reference item )
  713. {
  714. push_back_helper prolog(*this);
  715. new(prolog.internal_push_back_result()) T(item);
  716. return prolog.return_iterator_and_dismiss();
  717. }
  718. #if __TBB_CPP11_RVALUE_REF_PRESENT
  719. //! Push item, move-aware
  720. /** Returns iterator pointing to the new element. */
  721. iterator push_back( T&& item )
  722. {
  723. push_back_helper prolog(*this);
  724. new(prolog.internal_push_back_result()) T(std::move(item));
  725. return prolog.return_iterator_and_dismiss();
  726. }
  727. #if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  728. //! Push item, create item "in place" with provided arguments
  729. /** Returns iterator pointing to the new element. */
  730. template<typename... Args>
  731. iterator emplace_back( Args&&... args )
  732. {
  733. push_back_helper prolog(*this);
  734. new(prolog.internal_push_back_result()) T(std::forward<Args>(args)...);
  735. return prolog.return_iterator_and_dismiss();
  736. }
  737. #endif //__TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  738. #endif //__TBB_CPP11_RVALUE_REF_PRESENT
  739. //! Get reference to element at given index.
  740. /** This method is thread-safe for concurrent reads, and also while growing the vector,
  741. as long as the calling thread has checked that index < size(). */
  742. reference operator[]( size_type index ) {
  743. return internal_subscript(index);
  744. }
  745. //! Get const reference to element at given index.
  746. const_reference operator[]( size_type index ) const {
  747. return internal_subscript(index);
  748. }
  749. //! Get reference to element at given index. Throws exceptions on errors.
  750. reference at( size_type index ) {
  751. return internal_subscript_with_exceptions(index);
  752. }
  753. //! Get const reference to element at given index. Throws exceptions on errors.
  754. const_reference at( size_type index ) const {
  755. return internal_subscript_with_exceptions(index);
  756. }
  757. //! Get range for iterating with parallel algorithms
  758. range_type range( size_t grainsize = 1 ) {
  759. return range_type( begin(), end(), grainsize );
  760. }
  761. //! Get const range for iterating with parallel algorithms
  762. const_range_type range( size_t grainsize = 1 ) const {
  763. return const_range_type( begin(), end(), grainsize );
  764. }
  765. //------------------------------------------------------------------------
  766. // Capacity
  767. //------------------------------------------------------------------------
  768. //! Return size of vector. It may include elements under construction
  769. size_type size() const {
  770. size_type sz = my_early_size, cp = internal_capacity();
  771. return cp < sz ? cp : sz;
  772. }
  773. //! Return false if vector is not empty or has elements under construction at least.
  774. bool empty() const {return !my_early_size;}
  775. //! Maximum size to which array can grow without allocating more memory. Concurrent allocations are not included in the value.
  776. size_type capacity() const {return internal_capacity();}
  777. //! Allocate enough space to grow to size n without having to allocate more memory later.
  778. /** Like most of the methods provided for STL compatibility, this method is *not* thread safe.
  779. The capacity afterwards may be bigger than the requested reservation. */
  780. void reserve( size_type n ) {
  781. if( n )
  782. internal_reserve(n, sizeof(T), max_size());
  783. }
  784. //! Resize the vector. Not thread-safe.
  785. void resize( size_type n ) {
  786. internal_resize( n, sizeof(T), max_size(), NULL, &destroy_array, &initialize_array );
  787. }
  788. //! Resize the vector, copy t for new elements. Not thread-safe.
  789. void resize( size_type n, const_reference t ) {
  790. internal_resize( n, sizeof(T), max_size(), static_cast<const void*>(&t), &destroy_array, &initialize_array_by );
  791. }
  792. //! Optimize memory usage and fragmentation.
  793. void shrink_to_fit();
  794. //! Upper bound on argument to reserve.
  795. size_type max_size() const {return (~size_type(0))/sizeof(T);}
  796. //------------------------------------------------------------------------
  797. // STL support
  798. //------------------------------------------------------------------------
  799. //! start iterator
  800. iterator begin() {return iterator(*this,0);}
  801. //! end iterator
  802. iterator end() {return iterator(*this,size());}
  803. //! start const iterator
  804. const_iterator begin() const {return const_iterator(*this,0);}
  805. //! end const iterator
  806. const_iterator end() const {return const_iterator(*this,size());}
  807. //! start const iterator
  808. const_iterator cbegin() const {return const_iterator(*this,0);}
  809. //! end const iterator
  810. const_iterator cend() const {return const_iterator(*this,size());}
  811. //! reverse start iterator
  812. reverse_iterator rbegin() {return reverse_iterator(end());}
  813. //! reverse end iterator
  814. reverse_iterator rend() {return reverse_iterator(begin());}
  815. //! reverse start const iterator
  816. const_reverse_iterator rbegin() const {return const_reverse_iterator(end());}
  817. //! reverse end const iterator
  818. const_reverse_iterator rend() const {return const_reverse_iterator(begin());}
  819. //! reverse start const iterator
  820. const_reverse_iterator crbegin() const {return const_reverse_iterator(end());}
  821. //! reverse end const iterator
  822. const_reverse_iterator crend() const {return const_reverse_iterator(begin());}
  823. //! the first item
  824. reference front() {
  825. __TBB_ASSERT( size()>0, NULL);
  826. const segment_value_t& segment_value = my_segment[0].template load<relaxed>();
  827. return (segment_value.template pointer<T>())[0];
  828. }
  829. //! the first item const
  830. const_reference front() const {
  831. __TBB_ASSERT( size()>0, NULL);
  832. const segment_value_t& segment_value = my_segment[0].template load<relaxed>();
  833. return (segment_value.template pointer<const T>())[0];
  834. }
  835. //! the last item
  836. reference back() {
  837. __TBB_ASSERT( size()>0, NULL);
  838. return internal_subscript( size()-1 );
  839. }
  840. //! the last item const
  841. const_reference back() const {
  842. __TBB_ASSERT( size()>0, NULL);
  843. return internal_subscript( size()-1 );
  844. }
  845. //! return allocator object
  846. allocator_type get_allocator() const { return this->my_allocator; }
  847. //! assign n items by copying t item
  848. void assign(size_type n, const_reference t) {
  849. clear();
  850. internal_resize( n, sizeof(T), max_size(), static_cast<const void*>(&t), &destroy_array, &initialize_array_by );
  851. }
  852. //! assign range [first, last)
  853. template<class I>
  854. void assign(I first, I last) {
  855. clear(); internal_assign_range( first, last, static_cast<is_integer_tag<std::numeric_limits<I>::is_integer> *>(0) );
  856. }
  857. #if __TBB_INITIALIZER_LISTS_PRESENT
  858. //! assigns an initializer list
  859. void assign(std::initializer_list<T> init_list) {
  860. clear(); internal_assign_iterators( init_list.begin(), init_list.end());
  861. }
  862. #endif //# __TBB_INITIALIZER_LISTS_PRESENT
  863. //! swap two instances
  864. void swap(concurrent_vector &vector) {
  865. typedef typename tbb::internal::allocator_traits<A>::propagate_on_container_swap pocs_t;
  866. if( this != &vector && (this->my_allocator == vector.my_allocator || pocs_t::value) ) {
  867. concurrent_vector_base_v3::internal_swap(static_cast<concurrent_vector_base_v3&>(vector));
  868. tbb::internal::allocator_swap(this->my_allocator, vector.my_allocator, pocs_t());
  869. }
  870. }
  871. //! Clear container while keeping memory allocated.
  872. /** To free up the memory, use in conjunction with method compact(). Not thread safe **/
  873. void clear() {
  874. internal_clear(&destroy_array);
  875. }
  876. //! Clear and destroy vector.
  877. ~concurrent_vector() {
  878. segment_t *table = my_segment.load<relaxed>();
  879. internal_free_segments( table, internal_clear(&destroy_array), my_first_block.load<relaxed>() );
  880. // base class destructor call should be then
  881. }
  882. const internal::concurrent_vector_base_v3 &internal_vector_base() const { return *this; }
  883. private:
  884. //! Allocate k items
  885. static void *internal_allocator(internal::concurrent_vector_base_v3 &vb, size_t k) {
  886. return static_cast<concurrent_vector<T, A>&>(vb).my_allocator.allocate(k);
  887. }
  888. //! Free k segments from table
  889. void internal_free_segments(segment_t table[], segment_index_t k, segment_index_t first_block);
  890. //! Get reference to element at given index.
  891. T& internal_subscript( size_type index ) const;
  892. //! Get reference to element at given index with errors checks
  893. T& internal_subscript_with_exceptions( size_type index ) const;
  894. //! assign n items by copying t
  895. void internal_assign_n(size_type n, const_pointer p) {
  896. internal_resize( n, sizeof(T), max_size(), static_cast<const void*>(p), &destroy_array, p? &initialize_array_by : &initialize_array );
  897. }
  898. //! True/false function override helper
  899. /* Functions declarations:
  900. * void foo(is_integer_tag<true>*);
  901. * void foo(is_integer_tag<false>*);
  902. * Usage example:
  903. * foo(static_cast<is_integer_tag<std::numeric_limits<T>::is_integer>*>(0));
  904. */
  905. template<bool B> class is_integer_tag;
  906. //! assign integer items by copying when arguments are treated as iterators. See C++ Standard 2003 23.1.1p9
  907. template<class I>
  908. void internal_assign_range(I first, I last, is_integer_tag<true> *) {
  909. internal_assign_n(static_cast<size_type>(first), &static_cast<T&>(last));
  910. }
  911. //! inline proxy assign by iterators
  912. template<class I>
  913. void internal_assign_range(I first, I last, is_integer_tag<false> *) {
  914. internal_assign_iterators(first, last);
  915. }
  916. //! assign by iterators
  917. template<class I>
  918. void internal_assign_iterators(I first, I last);
  919. //these functions are marked __TBB_EXPORTED_FUNC as they are called from within the library
  920. //! Construct n instances of T, starting at "begin".
  921. static void __TBB_EXPORTED_FUNC initialize_array( void* begin, const void*, size_type n );
  922. //! Copy-construct n instances of T, starting at "begin".
  923. static void __TBB_EXPORTED_FUNC initialize_array_by( void* begin, const void* src, size_type n );
  924. //! Copy-construct n instances of T by copying single element pointed to by src, starting at "dst".
  925. static void __TBB_EXPORTED_FUNC copy_array( void* dst, const void* src, size_type n );
  926. #if __TBB_MOVE_IF_NOEXCEPT_PRESENT
  927. //! Either opy or move-construct n instances of T, starting at "dst" by copying according element of src array.
  928. static void __TBB_EXPORTED_FUNC move_array_if_noexcept( void* dst, const void* src, size_type n );
  929. #endif //__TBB_MOVE_IF_NO_EXCEPT_PRESENT
  930. #if __TBB_CPP11_RVALUE_REF_PRESENT
  931. //! Move-construct n instances of T, starting at "dst" by copying according element of src array.
  932. static void __TBB_EXPORTED_FUNC move_array( void* dst, const void* src, size_type n );
  933. //! Move-assign (using operator=) n instances of T, starting at "dst" by assigning according element of src array.
  934. static void __TBB_EXPORTED_FUNC move_assign_array( void* dst, const void* src, size_type n );
  935. #endif
  936. //! Copy-construct n instances of T, starting at "dst" by iterator range of [p_type_erased_iterator, p_type_erased_iterator+n).
  937. template<typename Iterator>
  938. static void __TBB_EXPORTED_FUNC copy_range( void* dst, const void* p_type_erased_iterator, size_type n );
  939. //! Assign (using operator=) n instances of T, starting at "dst" by assigning according element of src array.
  940. static void __TBB_EXPORTED_FUNC assign_array( void* dst, const void* src, size_type n );
  941. //! Destroy n instances of T, starting at "begin".
  942. static void __TBB_EXPORTED_FUNC destroy_array( void* begin, size_type n );
  943. //! Exception-aware helper class for filling a segment by exception-danger operators of user class
  944. class internal_loop_guide : internal::no_copy {
  945. public:
  946. const pointer array;
  947. const size_type n;
  948. size_type i;
  949. static const T* as_const_pointer(const void *ptr) { return static_cast<const T *>(ptr); }
  950. static T* as_pointer(const void *src) { return static_cast<T*>(const_cast<void *>(src)); }
  951. internal_loop_guide(size_type ntrials, void *ptr)
  952. : array(as_pointer(ptr)), n(ntrials), i(0) {}
  953. void init() { for(; i < n; ++i) new( &array[i] ) T(); }
  954. void init(const void *src) { for(; i < n; ++i) new( &array[i] ) T(*as_const_pointer(src)); }
  955. void copy(const void *src) { for(; i < n; ++i) new( &array[i] ) T(as_const_pointer(src)[i]); }
  956. void assign(const void *src) { for(; i < n; ++i) array[i] = as_const_pointer(src)[i]; }
  957. #if __TBB_CPP11_RVALUE_REF_PRESENT
  958. void move_assign(const void *src) { for(; i < n; ++i) array[i] = std::move(as_pointer(src)[i]); }
  959. void move_construct(const void *src) { for(; i < n; ++i) new( &array[i] ) T( std::move(as_pointer(src)[i]) ); }
  960. #endif
  961. #if __TBB_MOVE_IF_NOEXCEPT_PRESENT
  962. void move_construct_if_noexcept(const void *src) { for(; i < n; ++i) new( &array[i] ) T( std::move_if_noexcept(as_pointer(src)[i]) ); }
  963. #endif //__TBB_MOVE_IF_NOEXCEPT_PRESENT
  964. //TODO: rename to construct_range
  965. template<class I> void iterate(I &src) { for(; i < n; ++i, ++src) new( &array[i] ) T( *src ); }
  966. ~internal_loop_guide() {
  967. if(i < n) {// if an exception was raised, fill the rest of items with zeros
  968. internal::handle_unconstructed_elements(array+i, n-i);
  969. }
  970. }
  971. };
  972. struct push_back_helper : internal::no_copy{
  973. struct element_construction_guard : internal::no_copy{
  974. pointer element;
  975. element_construction_guard(pointer an_element) : element (an_element){}
  976. void dismiss(){ element = NULL; }
  977. ~element_construction_guard(){
  978. if (element){
  979. internal::handle_unconstructed_elements(element, 1);
  980. }
  981. }
  982. };
  983. concurrent_vector & v;
  984. size_type k;
  985. element_construction_guard g;
  986. push_back_helper(concurrent_vector & vector) :
  987. v(vector),
  988. g (static_cast<T*>(v.internal_push_back(sizeof(T),k)))
  989. {}
  990. pointer internal_push_back_result(){ return g.element;}
  991. iterator return_iterator_and_dismiss(){
  992. pointer ptr = g.element;
  993. g.dismiss();
  994. return iterator(v, k, ptr);
  995. }
  996. };
  997. };
  998. #if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT
  999. // Deduction guide for the constructor from two iterators
  1000. template<typename I,
  1001. typename T = typename std::iterator_traits<I>::value_type,
  1002. typename A = cache_aligned_allocator<T>
  1003. > concurrent_vector(I, I, const A& = A())
  1004. -> concurrent_vector<T, A>;
  1005. // Deduction guide for the constructor from a vector and allocator
  1006. template<typename T, typename A1, typename A2>
  1007. concurrent_vector(const concurrent_vector<T, A1> &, const A2 &)
  1008. -> concurrent_vector<T, A2>;
  1009. // Deduction guide for the constructor from an initializer_list
  1010. template<typename T, typename A = cache_aligned_allocator<T>
  1011. > concurrent_vector(std::initializer_list<T>, const A& = A())
  1012. -> concurrent_vector<T, A>;
  1013. #endif /* __TBB_CPP17_DEDUCTION_GUIDES_PRESENT */
  1014. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1015. #pragma warning (push)
  1016. #pragma warning (disable: 4701) // potentially uninitialized local variable "old"
  1017. #endif
  1018. template<typename T, class A>
  1019. void concurrent_vector<T, A>::shrink_to_fit() {
  1020. internal_segments_table old;
  1021. __TBB_TRY {
  1022. internal_array_op2 copy_or_move_array =
  1023. #if __TBB_MOVE_IF_NOEXCEPT_PRESENT
  1024. &move_array_if_noexcept
  1025. #else
  1026. &copy_array
  1027. #endif
  1028. ;
  1029. if( internal_compact( sizeof(T), &old, &destroy_array, copy_or_move_array ) )
  1030. internal_free_segments( old.table, pointers_per_long_table, old.first_block ); // free joined and unnecessary segments
  1031. } __TBB_CATCH(...) {
  1032. if( old.first_block ) // free segment allocated for compacting. Only for support of exceptions in ctor of user T[ype]
  1033. internal_free_segments( old.table, 1, old.first_block );
  1034. __TBB_RETHROW();
  1035. }
  1036. }
  1037. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1038. #pragma warning (pop)
  1039. #endif // warning 4701 is back
  1040. template<typename T, class A>
  1041. void concurrent_vector<T, A>::internal_free_segments(segment_t table[], segment_index_t k, segment_index_t first_block) {
  1042. // Free the arrays
  1043. while( k > first_block ) {
  1044. --k;
  1045. segment_value_t segment_value = table[k].load<relaxed>();
  1046. table[k].store<relaxed>(segment_not_used());
  1047. if( segment_value == segment_allocated() ) // check for correct segment pointer
  1048. this->my_allocator.deallocate( (segment_value.pointer<T>()), segment_size(k) );
  1049. }
  1050. segment_value_t segment_value = table[0].load<relaxed>();
  1051. if( segment_value == segment_allocated() ) {
  1052. __TBB_ASSERT( first_block > 0, NULL );
  1053. while(k > 0) table[--k].store<relaxed>(segment_not_used());
  1054. this->my_allocator.deallocate( (segment_value.pointer<T>()), segment_size(first_block) );
  1055. }
  1056. }
  1057. template<typename T, class A>
  1058. T& concurrent_vector<T, A>::internal_subscript( size_type index ) const {
  1059. //TODO: unify both versions of internal_subscript
  1060. __TBB_ASSERT( index < my_early_size, "index out of bounds" );
  1061. size_type j = index;
  1062. segment_index_t k = segment_base_index_of( j );
  1063. __TBB_ASSERT( my_segment.load<acquire>() != my_storage || k < pointers_per_short_table, "index is being allocated" );
  1064. //no need in load with acquire (load<acquire>) since thread works in own space or gets
  1065. //the information about added elements via some form of external synchronization
  1066. //TODO: why not make a load of my_segment relaxed as well ?
  1067. //TODO: add an assertion that my_segment[k] is properly aligned to please ITT
  1068. segment_value_t segment_value = my_segment[k].template load<relaxed>();
  1069. __TBB_ASSERT( segment_value != segment_allocation_failed(), "the instance is broken by bad allocation. Use at() instead" );
  1070. __TBB_ASSERT( segment_value != segment_not_used(), "index is being allocated" );
  1071. return (( segment_value.pointer<T>()))[j];
  1072. }
  1073. template<typename T, class A>
  1074. T& concurrent_vector<T, A>::internal_subscript_with_exceptions( size_type index ) const {
  1075. if( index >= my_early_size )
  1076. internal::throw_exception(internal::eid_out_of_range); // throw std::out_of_range
  1077. size_type j = index;
  1078. segment_index_t k = segment_base_index_of( j );
  1079. //TODO: refactor this condition into separate helper function, e.g. fits_into_small_table
  1080. if( my_segment.load<acquire>() == my_storage && k >= pointers_per_short_table )
  1081. internal::throw_exception(internal::eid_segment_range_error); // throw std::range_error
  1082. // no need in load with acquire (load<acquire>) since thread works in own space or gets
  1083. //the information about added elements via some form of external synchronization
  1084. //TODO: why not make a load of my_segment relaxed as well ?
  1085. //TODO: add an assertion that my_segment[k] is properly aligned to please ITT
  1086. segment_value_t segment_value = my_segment[k].template load<relaxed>();
  1087. enforce_segment_allocated(segment_value, internal::eid_index_range_error);
  1088. return (segment_value.pointer<T>())[j];
  1089. }
  1090. template<typename T, class A> template<class I>
  1091. void concurrent_vector<T, A>::internal_assign_iterators(I first, I last) {
  1092. __TBB_ASSERT(my_early_size == 0, NULL);
  1093. size_type n = std::distance(first, last);
  1094. if( !n ) return;
  1095. internal_reserve(n, sizeof(T), max_size());
  1096. my_early_size = n;
  1097. segment_index_t k = 0;
  1098. //TODO: unify segment iteration code with concurrent_base_v3::helper
  1099. size_type sz = segment_size( my_first_block );
  1100. while( sz < n ) {
  1101. internal_loop_guide loop(sz, my_segment[k].template load<relaxed>().template pointer<void>());
  1102. loop.iterate(first);
  1103. n -= sz;
  1104. if( !k ) k = my_first_block;
  1105. else { ++k; sz <<= 1; }
  1106. }
  1107. internal_loop_guide loop(n, my_segment[k].template load<relaxed>().template pointer<void>());
  1108. loop.iterate(first);
  1109. }
  1110. template<typename T, class A>
  1111. void concurrent_vector<T, A>::initialize_array( void* begin, const void *, size_type n ) {
  1112. internal_loop_guide loop(n, begin); loop.init();
  1113. }
  1114. template<typename T, class A>
  1115. void concurrent_vector<T, A>::initialize_array_by( void* begin, const void *src, size_type n ) {
  1116. internal_loop_guide loop(n, begin); loop.init(src);
  1117. }
  1118. template<typename T, class A>
  1119. void concurrent_vector<T, A>::copy_array( void* dst, const void* src, size_type n ) {
  1120. internal_loop_guide loop(n, dst); loop.copy(src);
  1121. }
  1122. #if __TBB_CPP11_RVALUE_REF_PRESENT
  1123. template<typename T, class A>
  1124. void concurrent_vector<T, A>::move_array( void* dst, const void* src, size_type n ) {
  1125. internal_loop_guide loop(n, dst); loop.move_construct(src);
  1126. }
  1127. template<typename T, class A>
  1128. void concurrent_vector<T, A>::move_assign_array( void* dst, const void* src, size_type n ) {
  1129. internal_loop_guide loop(n, dst); loop.move_assign(src);
  1130. }
  1131. #endif
  1132. #if __TBB_MOVE_IF_NOEXCEPT_PRESENT
  1133. template<typename T, class A>
  1134. void concurrent_vector<T, A>::move_array_if_noexcept( void* dst, const void* src, size_type n ) {
  1135. internal_loop_guide loop(n, dst); loop.move_construct_if_noexcept(src);
  1136. }
  1137. #endif //__TBB_MOVE_IF_NOEXCEPT_PRESENT
  1138. template<typename T, class A>
  1139. template<typename I>
  1140. void concurrent_vector<T, A>::copy_range( void* dst, const void* p_type_erased_iterator, size_type n ){
  1141. internal_loop_guide loop(n, dst);
  1142. loop.iterate( *(static_cast<I*>(const_cast<void*>(p_type_erased_iterator))) );
  1143. }
  1144. template<typename T, class A>
  1145. void concurrent_vector<T, A>::assign_array( void* dst, const void* src, size_type n ) {
  1146. internal_loop_guide loop(n, dst); loop.assign(src);
  1147. }
  1148. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1149. // Workaround for overzealous compiler warning
  1150. #pragma warning (push)
  1151. #pragma warning (disable: 4189)
  1152. #endif
  1153. template<typename T, class A>
  1154. void concurrent_vector<T, A>::destroy_array( void* begin, size_type n ) {
  1155. T* array = static_cast<T*>(begin);
  1156. for( size_type j=n; j>0; --j )
  1157. array[j-1].~T(); // destructors are supposed to not throw any exceptions
  1158. }
  1159. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1160. #pragma warning (pop)
  1161. #endif // warning 4189 is back
  1162. // concurrent_vector's template functions
  1163. template<typename T, class A1, class A2>
  1164. inline bool operator==(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b) {
  1165. //TODO: call size() only once per vector (in operator==)
  1166. // Simply: return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
  1167. if(a.size() != b.size()) return false;
  1168. typename concurrent_vector<T, A1>::const_iterator i(a.begin());
  1169. typename concurrent_vector<T, A2>::const_iterator j(b.begin());
  1170. for(; i != a.end(); ++i, ++j)
  1171. if( !(*i == *j) ) return false;
  1172. return true;
  1173. }
  1174. template<typename T, class A1, class A2>
  1175. inline bool operator!=(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b)
  1176. { return !(a == b); }
  1177. template<typename T, class A1, class A2>
  1178. inline bool operator<(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b)
  1179. { return (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())); }
  1180. template<typename T, class A1, class A2>
  1181. inline bool operator>(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b)
  1182. { return b < a; }
  1183. template<typename T, class A1, class A2>
  1184. inline bool operator<=(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b)
  1185. { return !(b < a); }
  1186. template<typename T, class A1, class A2>
  1187. inline bool operator>=(const concurrent_vector<T, A1> &a, const concurrent_vector<T, A2> &b)
  1188. { return !(a < b); }
  1189. template<typename T, class A>
  1190. inline void swap(concurrent_vector<T, A> &a, concurrent_vector<T, A> &b)
  1191. { a.swap( b ); }
  1192. } // namespace tbb
  1193. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1194. #pragma warning (pop)
  1195. #endif // warning 4267,4127 are back
  1196. #undef __TBB_concurrent_vector_H_include_area
  1197. #include "internal/_warning_suppress_disable_notice.h"
  1198. #endif /* __TBB_concurrent_vector_H */