libstdc++
balanced_quicksort.h
Go to the documentation of this file.
00001 // -*- C++ -*-
00002 
00003 // Copyright (C) 2007-2019 Free Software Foundation, Inc.
00004 //
00005 // This file is part of the GNU ISO C++ Library.  This library is free
00006 // software; you can redistribute it and/or modify it under the terms
00007 // of the GNU General Public License as published by the Free Software
00008 // Foundation; either version 3, or (at your option) any later
00009 // version.
00010 
00011 // This library is distributed in the hope that it will be useful, but
00012 // WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 // General Public License for more details.
00015 
00016 // Under Section 7 of GPL version 3, you are granted additional
00017 // permissions described in the GCC Runtime Library Exception, version
00018 // 3.1, as published by the Free Software Foundation.
00019 
00020 // You should have received a copy of the GNU General Public License and
00021 // a copy of the GCC Runtime Library Exception along with this program;
00022 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00023 // <http://www.gnu.org/licenses/>.
00024 
00025 /** @file parallel/balanced_quicksort.h
00026  *  @brief Implementation of a dynamically load-balanced parallel quicksort.
00027  *
00028  *  It works in-place and needs only logarithmic extra memory.
00029  *  The algorithm is similar to the one proposed in
00030  *
00031  *  P. Tsigas and Y. Zhang.
00032  *  A simple, fast parallel implementation of quicksort and
00033  *  its performance evaluation on SUN enterprise 10000.
00034  *  In 11th Euromicro Conference on Parallel, Distributed and
00035  *  Network-Based Processing, page 372, 2003.
00036  *
00037  *  This file is a GNU parallel extension to the Standard C++ Library.
00038  */
00039 
00040 // Written by Johannes Singler.
00041 
00042 #ifndef _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H
00043 #define _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H 1
00044 
00045 #include <parallel/basic_iterator.h>
00046 #include <bits/stl_algo.h>
00047 #include <bits/stl_function.h>
00048 
00049 #include <parallel/settings.h>
00050 #include <parallel/partition.h>
00051 #include <parallel/random_number.h>
00052 #include <parallel/queue.h>
00053 
00054 #if _GLIBCXX_PARALLEL_ASSERTIONS
00055 #include <parallel/checkers.h>
00056 #ifdef _GLIBCXX_HAVE_UNISTD_H
00057 #include <unistd.h>
00058 #endif
00059 #endif
00060 
00061 namespace __gnu_parallel
00062 {
00063   /** @brief Information local to one thread in the parallel quicksort run. */
00064   template<typename _RAIter>
00065     struct _QSBThreadLocal
00066     {
00067       typedef std::iterator_traits<_RAIter> _TraitsType;
00068       typedef typename _TraitsType::difference_type _DifferenceType;
00069 
00070       /** @brief Continuous part of the sequence, described by an
00071       iterator pair. */
00072       typedef std::pair<_RAIter, _RAIter> _Piece;
00073 
00074       /** @brief Initial piece to work on. */
00075       _Piece _M_initial;
00076 
00077       /** @brief Work-stealing queue. */
00078       _RestrictedBoundedConcurrentQueue<_Piece> _M_leftover_parts;
00079 
00080       /** @brief Number of threads involved in this algorithm. */
00081       _ThreadIndex _M_num_threads;
00082 
00083       /** @brief Pointer to a counter of elements left over to sort. */
00084       volatile _DifferenceType* _M_elements_leftover;
00085 
00086       /** @brief The complete sequence to sort. */
00087       _Piece _M_global;
00088 
00089       /** @brief Constructor.
00090        *  @param __queue_size size of the work-stealing queue. */
00091       _QSBThreadLocal(int __queue_size) : _M_leftover_parts(__queue_size) { }
00092     };
00093 
00094   /** @brief Balanced quicksort divide step.
00095     *  @param __begin Begin iterator of subsequence.
00096     *  @param __end End iterator of subsequence.
00097     *  @param __comp Comparator.
00098     *  @param __num_threads Number of threads that are allowed to work on
00099     *  this part.
00100     *  @pre @c (__end-__begin)>=1 */
00101   template<typename _RAIter, typename _Compare>
00102     typename std::iterator_traits<_RAIter>::difference_type
00103     __qsb_divide(_RAIter __begin, _RAIter __end,
00104                  _Compare __comp, _ThreadIndex __num_threads)
00105     {
00106       _GLIBCXX_PARALLEL_ASSERT(__num_threads > 0);
00107 
00108       typedef std::iterator_traits<_RAIter> _TraitsType;
00109       typedef typename _TraitsType::value_type _ValueType;
00110       typedef typename _TraitsType::difference_type _DifferenceType;
00111 
00112       _RAIter __pivot_pos =
00113         __median_of_three_iterators(__begin, __begin + (__end - __begin) / 2,
00114                                     __end  - 1, __comp);
00115 
00116 #if defined(_GLIBCXX_PARALLEL_ASSERTIONS)
00117       // Must be in between somewhere.
00118       _DifferenceType __n = __end - __begin;
00119 
00120       _GLIBCXX_PARALLEL_ASSERT((!__comp(*__pivot_pos, *__begin)
00121                                 && !__comp(*(__begin + __n / 2),
00122                                            *__pivot_pos))
00123                                || (!__comp(*__pivot_pos, *__begin)
00124                                    && !__comp(*(__end - 1), *__pivot_pos))
00125                                || (!__comp(*__pivot_pos, *(__begin + __n / 2))
00126                                    && !__comp(*__begin, *__pivot_pos))
00127                                || (!__comp(*__pivot_pos, *(__begin + __n / 2))
00128                                    && !__comp(*(__end - 1), *__pivot_pos))
00129                                || (!__comp(*__pivot_pos, *(__end - 1))
00130                                    && !__comp(*__begin, *__pivot_pos))
00131                                || (!__comp(*__pivot_pos, *(__end - 1))
00132                                    && !__comp(*(__begin + __n / 2),
00133                                               *__pivot_pos)));
00134 #endif
00135 
00136       // Swap pivot value to end.
00137       if (__pivot_pos != (__end - 1))
00138         std::iter_swap(__pivot_pos, __end - 1);
00139       __pivot_pos = __end - 1;
00140 
00141       __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool>
00142         __pred(__comp, *__pivot_pos);
00143 
00144       // Divide, returning __end - __begin - 1 in the worst case.
00145       _DifferenceType __split_pos = __parallel_partition(__begin, __end - 1,
00146                                                          __pred,
00147                                                          __num_threads);
00148 
00149       // Swap back pivot to middle.
00150       std::iter_swap(__begin + __split_pos, __pivot_pos);
00151       __pivot_pos = __begin + __split_pos;
00152 
00153 #if _GLIBCXX_PARALLEL_ASSERTIONS
00154       _RAIter __r;
00155       for (__r = __begin; __r != __pivot_pos; ++__r)
00156         _GLIBCXX_PARALLEL_ASSERT(__comp(*__r, *__pivot_pos));
00157       for (; __r != __end; ++__r)
00158         _GLIBCXX_PARALLEL_ASSERT(!__comp(*__r, *__pivot_pos));
00159 #endif
00160 
00161       return __split_pos;
00162     }
00163 
00164   /** @brief Quicksort conquer step.
00165     *  @param __tls Array of thread-local storages.
00166     *  @param __begin Begin iterator of subsequence.
00167     *  @param __end End iterator of subsequence.
00168     *  @param __comp Comparator.
00169     *  @param __iam Number of the thread processing this function.
00170     *  @param __num_threads
00171     *          Number of threads that are allowed to work on this part. */
00172   template<typename _RAIter, typename _Compare>
00173     void
00174     __qsb_conquer(_QSBThreadLocal<_RAIter>** __tls,
00175                   _RAIter __begin, _RAIter __end,
00176                   _Compare __comp,
00177                   _ThreadIndex __iam, _ThreadIndex __num_threads,
00178                   bool __parent_wait)
00179     {
00180       typedef std::iterator_traits<_RAIter> _TraitsType;
00181       typedef typename _TraitsType::value_type _ValueType;
00182       typedef typename _TraitsType::difference_type _DifferenceType;
00183 
00184       _DifferenceType __n = __end - __begin;
00185 
00186       if (__num_threads <= 1 || __n <= 1)
00187         {
00188           __tls[__iam]->_M_initial.first  = __begin;
00189           __tls[__iam]->_M_initial.second = __end;
00190 
00191           __qsb_local_sort_with_helping(__tls, __comp, __iam, __parent_wait);
00192 
00193           return;
00194         }
00195 
00196       // Divide step.
00197       _DifferenceType __split_pos =
00198         __qsb_divide(__begin, __end, __comp, __num_threads);
00199 
00200 #if _GLIBCXX_PARALLEL_ASSERTIONS
00201       _GLIBCXX_PARALLEL_ASSERT(0 <= __split_pos &&
00202                                __split_pos < (__end - __begin));
00203 #endif
00204 
00205       _ThreadIndex
00206         __num_threads_leftside = std::max<_ThreadIndex>
00207         (1, std::min<_ThreadIndex>(__num_threads - 1, __split_pos
00208                                    * __num_threads / __n));
00209 
00210 #     pragma omp atomic
00211       *__tls[__iam]->_M_elements_leftover -= (_DifferenceType)1;
00212 
00213       // Conquer step.
00214 #     pragma omp parallel num_threads(2)
00215       {
00216         bool __wait;
00217         if(omp_get_num_threads() < 2)
00218           __wait = false;
00219         else
00220           __wait = __parent_wait;
00221 
00222 #       pragma omp sections
00223         {
00224 #         pragma omp section
00225           {
00226             __qsb_conquer(__tls, __begin, __begin + __split_pos, __comp,
00227                           __iam, __num_threads_leftside, __wait);
00228             __wait = __parent_wait;
00229           }
00230           // The pivot_pos is left in place, to ensure termination.
00231 #         pragma omp section
00232           {
00233             __qsb_conquer(__tls, __begin + __split_pos + 1, __end, __comp,
00234                           __iam + __num_threads_leftside,
00235                           __num_threads - __num_threads_leftside, __wait);
00236             __wait = __parent_wait;
00237           }
00238         }
00239       }
00240     }
00241 
00242   /**
00243     *  @brief Quicksort step doing load-balanced local sort.
00244     *  @param __tls Array of thread-local storages.
00245     *  @param __comp Comparator.
00246     *  @param __iam Number of the thread processing this function.
00247     */
00248   template<typename _RAIter, typename _Compare>
00249     void
00250     __qsb_local_sort_with_helping(_QSBThreadLocal<_RAIter>** __tls,
00251                                   _Compare& __comp, _ThreadIndex __iam,
00252                                   bool __wait)
00253     {
00254       typedef std::iterator_traits<_RAIter> _TraitsType;
00255       typedef typename _TraitsType::value_type _ValueType;
00256       typedef typename _TraitsType::difference_type _DifferenceType;
00257       typedef std::pair<_RAIter, _RAIter> _Piece;
00258 
00259       _QSBThreadLocal<_RAIter>& __tl = *__tls[__iam];
00260 
00261       _DifferenceType
00262         __base_case_n = _Settings::get().sort_qsb_base_case_maximal_n;
00263       if (__base_case_n < 2)
00264         __base_case_n = 2;
00265       _ThreadIndex __num_threads = __tl._M_num_threads;
00266 
00267       // Every thread has its own random number generator.
00268       _RandomNumber __rng(__iam + 1);
00269 
00270       _Piece __current = __tl._M_initial;
00271 
00272       _DifferenceType __elements_done = 0;
00273 #if _GLIBCXX_PARALLEL_ASSERTIONS
00274       _DifferenceType __total_elements_done = 0;
00275 #endif
00276 
00277       for (;;)
00278         {
00279           // Invariant: __current must be a valid (maybe empty) range.
00280           _RAIter __begin = __current.first, __end = __current.second;
00281           _DifferenceType __n = __end - __begin;
00282 
00283           if (__n > __base_case_n)
00284             {
00285               // Divide.
00286               _RAIter __pivot_pos = __begin +  __rng(__n);
00287 
00288               // Swap __pivot_pos value to end.
00289               if (__pivot_pos != (__end - 1))
00290                 std::iter_swap(__pivot_pos, __end - 1);
00291               __pivot_pos = __end - 1;
00292 
00293               __gnu_parallel::__binder2nd
00294                 <_Compare, _ValueType, _ValueType, bool>
00295                 __pred(__comp, *__pivot_pos);
00296 
00297               // Divide, leave pivot unchanged in last place.
00298               _RAIter __split_pos1, __split_pos2;
00299               __split_pos1 = __gnu_sequential::partition(__begin, __end - 1,
00300                                                          __pred);
00301 
00302               // Left side: < __pivot_pos; __right side: >= __pivot_pos.
00303 #if _GLIBCXX_PARALLEL_ASSERTIONS
00304               _GLIBCXX_PARALLEL_ASSERT(__begin <= __split_pos1
00305                                        && __split_pos1 < __end);
00306 #endif
00307               // Swap pivot back to middle.
00308               if (__split_pos1 != __pivot_pos)
00309                 std::iter_swap(__split_pos1, __pivot_pos);
00310               __pivot_pos = __split_pos1;
00311 
00312               // In case all elements are equal, __split_pos1 == 0.
00313               if ((__split_pos1 + 1 - __begin) < (__n >> 7)
00314                   || (__end - __split_pos1) < (__n >> 7))
00315                 {
00316                   // Very unequal split, one part smaller than one 128th
00317                   // elements not strictly larger than the pivot.
00318                   __gnu_parallel::__unary_negate<__gnu_parallel::__binder1st
00319                     <_Compare, _ValueType, _ValueType, bool>, _ValueType>
00320                     __pred(__gnu_parallel::__binder1st
00321                          <_Compare, _ValueType, _ValueType, bool>
00322                            (__comp, *__pivot_pos));
00323 
00324                   // Find other end of pivot-equal range.
00325                   __split_pos2 = __gnu_sequential::partition(__split_pos1 + 1,
00326                                                              __end, __pred);
00327                 }
00328               else
00329                 // Only skip the pivot.
00330                 __split_pos2 = __split_pos1 + 1;
00331 
00332               // Elements equal to pivot are done.
00333               __elements_done += (__split_pos2 - __split_pos1);
00334 #if _GLIBCXX_PARALLEL_ASSERTIONS
00335               __total_elements_done += (__split_pos2 - __split_pos1);
00336 #endif
00337               // Always push larger part onto stack.
00338               if (((__split_pos1 + 1) - __begin) < (__end - (__split_pos2)))
00339                 {
00340                   // Right side larger.
00341                   if ((__split_pos2) != __end)
00342                     __tl._M_leftover_parts.push_front
00343                       (std::make_pair(__split_pos2, __end));
00344 
00345                   //__current.first = __begin;    //already set anyway
00346                   __current.second = __split_pos1;
00347                   continue;
00348                 }
00349               else
00350                 {
00351                   // Left side larger.
00352                   if (__begin != __split_pos1)
00353                     __tl._M_leftover_parts.push_front(std::make_pair
00354                                                       (__begin, __split_pos1));
00355 
00356                   __current.first = __split_pos2;
00357                   //__current.second = __end;     //already set anyway
00358                   continue;
00359                 }
00360             }
00361           else
00362             {
00363               __gnu_sequential::sort(__begin, __end, __comp);
00364               __elements_done += __n;
00365 #if _GLIBCXX_PARALLEL_ASSERTIONS
00366               __total_elements_done += __n;
00367 #endif
00368 
00369               // Prefer own stack, small pieces.
00370               if (__tl._M_leftover_parts.pop_front(__current))
00371                 continue;
00372 
00373 #             pragma omp atomic
00374               *__tl._M_elements_leftover -= __elements_done;
00375 
00376               __elements_done = 0;
00377 
00378 #if _GLIBCXX_PARALLEL_ASSERTIONS
00379               double __search_start = omp_get_wtime();
00380 #endif
00381 
00382               // Look for new work.
00383               bool __successfully_stolen = false;
00384               while (__wait && *__tl._M_elements_leftover > 0
00385                      && !__successfully_stolen
00386 #if _GLIBCXX_PARALLEL_ASSERTIONS
00387                       // Possible dead-lock.
00388                      && (omp_get_wtime() < (__search_start + 1.0))
00389 #endif
00390                      )
00391                 {
00392                   _ThreadIndex __victim;
00393                   __victim = __rng(__num_threads);
00394 
00395                   // Large pieces.
00396                   __successfully_stolen = (__victim != __iam)
00397                     && __tls[__victim]->_M_leftover_parts.pop_back(__current);
00398                   if (!__successfully_stolen)
00399                     __yield();
00400 #if !defined(__ICC) && !defined(__ECC)
00401 #                 pragma omp flush
00402 #endif
00403                 }
00404 
00405 #if _GLIBCXX_PARALLEL_ASSERTIONS
00406               if (omp_get_wtime() >= (__search_start + 1.0))
00407                 {
00408                   sleep(1);
00409                   _GLIBCXX_PARALLEL_ASSERT(omp_get_wtime()
00410                                            < (__search_start + 1.0));
00411                 }
00412 #endif
00413               if (!__successfully_stolen)
00414                 {
00415 #if _GLIBCXX_PARALLEL_ASSERTIONS
00416                   _GLIBCXX_PARALLEL_ASSERT(*__tl._M_elements_leftover == 0);
00417 #endif
00418                   return;
00419                 }
00420             }
00421         }
00422     }
00423 
00424   /** @brief Top-level quicksort routine.
00425     *  @param __begin Begin iterator of sequence.
00426     *  @param __end End iterator of sequence.
00427     *  @param __comp Comparator.
00428     *  @param __num_threads Number of threads that are allowed to work on
00429     *  this part.
00430     */
00431   template<typename _RAIter, typename _Compare>
00432     void
00433     __parallel_sort_qsb(_RAIter __begin, _RAIter __end,
00434                         _Compare __comp, _ThreadIndex __num_threads)
00435     {
00436       _GLIBCXX_CALL(__end - __begin)
00437 
00438       typedef std::iterator_traits<_RAIter> _TraitsType;
00439       typedef typename _TraitsType::value_type _ValueType;
00440       typedef typename _TraitsType::difference_type _DifferenceType;
00441       typedef std::pair<_RAIter, _RAIter> _Piece;
00442 
00443       typedef _QSBThreadLocal<_RAIter> _TLSType;
00444 
00445       _DifferenceType __n = __end - __begin;
00446 
00447       if (__n <= 1)
00448         return;
00449 
00450       // At least one element per processor.
00451       if (__num_threads > __n)
00452         __num_threads = static_cast<_ThreadIndex>(__n);
00453 
00454       // Initialize thread local storage
00455       _TLSType** __tls = new _TLSType*[__num_threads];
00456       _DifferenceType __queue_size = (__num_threads
00457                                       * (_ThreadIndex)(__rd_log2(__n) + 1));
00458       for (_ThreadIndex __t = 0; __t < __num_threads; ++__t)
00459         __tls[__t] = new _QSBThreadLocal<_RAIter>(__queue_size);
00460 
00461       // There can never be more than ceil(__rd_log2(__n)) ranges on the
00462       // stack, because
00463       // 1. Only one processor pushes onto the stack
00464       // 2. The largest range has at most length __n
00465       // 3. Each range is larger than half of the range remaining
00466       volatile _DifferenceType __elements_leftover = __n;
00467       for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
00468         {
00469           __tls[__i]->_M_elements_leftover = &__elements_leftover;
00470           __tls[__i]->_M_num_threads = __num_threads;
00471           __tls[__i]->_M_global = std::make_pair(__begin, __end);
00472 
00473           // Just in case nothing is left to assign.
00474           __tls[__i]->_M_initial = std::make_pair(__end, __end);
00475         }
00476 
00477       // Main recursion call.
00478       __qsb_conquer(__tls, __begin, __begin + __n, __comp, 0,
00479                     __num_threads, true);
00480 
00481 #if _GLIBCXX_PARALLEL_ASSERTIONS
00482       // All stack must be empty.
00483       _Piece __dummy;
00484       for (_ThreadIndex __i = 1; __i < __num_threads; ++__i)
00485         _GLIBCXX_PARALLEL_ASSERT(
00486           !__tls[__i]->_M_leftover_parts.pop_back(__dummy));
00487 #endif
00488 
00489       for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
00490         delete __tls[__i];
00491       delete[] __tls;
00492     }
00493 } // namespace __gnu_parallel
00494 
00495 #endif /* _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H */