c1adcbfe93c91ea9b8f16f2dbbd6cedac237bac0
[platform/upstream/libzypp.git] / devel / devel.ma / MT.cc
1 //#include <thread>
2 #include <vector>
3 #include <boost/thread.hpp>
4 #include <zypp/base/Functional.h>
5
6 #include <zypp/base/Easy.h>
7 #include <zypp/base/Measure.h>
8 #include <zypp/base/Exception.h>
9 #include <zypp/base/String.h>
10
11 #include <zypp/base/LogTools.h>
12 #include <zypp/base/LogControl.h>
13
14 #include "zypp/ExternalProgram.h"
15
16 using std::endl;
17 using zypp::debug::Measure;
18
19 ///////////////////////////////////////////////////////////////////
20 namespace zypp
21 {
22   /** Run a number of tasks using \c threadCount threads.
23    *
24    * \code
25    * std::vector<function<void()>> tasks;
26    * for ( int i = 0; i < 100; ++i )
27    * {
28    *   tasks.push_back( [i]()
29    *   {
30    *     MIL << '[' << i << "]" << endl;
31    *   });
32    * }
33    * runTasks( tasks, 10 );
34    * \endcode
35    */
36   template <class _Function>
37   void runTasks( const std::vector<_Function>& tasks, size_t threadCount = 1 )
38   {
39     if ( threadCount )
40     {
41       boost::thread_group group;
42       const size_t taskCount = (tasks.size() / threadCount) + 1;
43       for ( size_t start = 0; start < tasks.size(); start += taskCount )
44       {
45         group.create_thread( [&tasks, start, taskCount]()
46         {
47           const size_t end = std::min( tasks.size(), start + taskCount );
48           for ( size_t i = start; i < end; ++i )
49             tasks[i]();
50         });
51       }
52       group.join_all();
53     }
54     else
55     {
56       for_( f, tasks.begin(), tasks.end() )
57         (*f)();
58     }
59   }
60 }
61 ///////////////////////////////////////////////////////////////////
62 using namespace zypp;
63 int main( int argc, char * argv[] )
64 try {
65   --argc;
66   ++argv;
67   zypp::base::LogControl::instance().logToStdErr();
68   INT << "===[START]==========================================" << endl;
69   ///////////////////////////////////////////////////////////////////
70
71   std::vector<function<void()>> tasks;
72   for ( int i = 0; i < 100; ++i )
73   {
74     tasks.push_back( [i]()
75     {
76       MIL << '[' << i << "]" << endl;
77     });
78   }
79   {
80     Measure x( "THREAD" );
81     runTasks( tasks, 100 );
82   }
83
84
85   ///////////////////////////////////////////////////////////////////
86   INT << "===[END]============================================" << endl << endl;
87   zypp::base::LogControl::instance().logNothing();
88   return 0;
89 }
90 catch ( const zypp::Exception & exp )
91 {
92   INT << exp << endl << exp.historyAsString();
93 }
94 catch (...)
95 {}
96