boost - multithreaded mergesort -


i wrote mergesort algorithm, , works fine. have commented recursive calls of function, , tried use boost::threads this:

#include <iostream> #include <vector> #include <boost/thread.hpp>  void merge_sort(std::vector <int> & tab, size_t beg, size_t end) {     if(beg < end)     {         size_t pivot = (beg + end) >> 1;          boost::thread left(merge_sort, tab, beg, pivot);         //merge_sort(tab, beg, pivot);         boost::thread right(merge_sort, tab, pivot + 1, end);         //merge_sort(tab, pivot + 1, end);         left.join();         right.join();          std::vector <int> buf (tab);         size_t = beg, j = pivot + 1, q = beg;         while (i <= pivot && j <= end)         {             if (buf[i] < buf[j])                 tab[q++] = buf[i++];             else                 tab[q++] = buf[j++];         }         while (i <= pivot)             tab[q++] = buf[i++];     } }  int main() {      const int myints[] = {30,29,28,27,26,25,1,2,3,4,5,6,7,24,23,22,21,20,19,18,8,9,10,11,17,16,15,13,45,12};     std::vector <int> kontener (myints, myints + sizeof(myints) / sizeof(int) );      merge_sort(kontener, 0, kontener.size() - 1);      for(std::vector <int>::iterator = kontener.begin(); != kontener.end(); it++)         std::cout << *it << " ";     std::cout << std::endl;      std::cin.sync();     std::cin.get();     return(0); } 

but i've got wrong output threads. :p therefore gratefull if tell me wrong code.

you not passing vector sub-threads reference, if may seem so. need use boost::ref or std::ref. note buffer has big section working on, there no point in copying entire vector time:

    boost::thread left(merge_sort, boost::ref(tab), beg, pivot);     boost::thread right(merge_sort, boost::ref(tab), pivot + 1, end);     left.join();     right.join();      std::vector <int> buf (tab.begin()+beg, tab.begin()+end+1);     size_t = beg, j = pivot + 1, q = beg;     while (i <= pivot && j <= end)     {         if (buf[i-beg] < buf[j-beg])             tab[q++] = buf[i++ - beg];         else             tab[q++] = buf[j++ - beg];     }     while (i <= pivot)         tab[q++] = buf[i++ - beg]; 

(also note code might bit cleaner if used iterators , standard algorithms, sake of simplicity, i've kept structure.)


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -