Change the log level INFO to DEBUG
[profile/tv/apps/web/browser.git] / core / Tools / WorkQueue.h
1 /*
2  * WorkQueue.h
3  *
4  *  Created on: Jun 10, 2014
5  *      Author: pchmielewski
6  */
7
8 #ifndef WORKQUEUE_H_
9 #define WORKQUEUE_H_
10
11 #include <boost/thread/thread.hpp>
12 #include <boost/thread/mutex.hpp>
13
14 namespace tizen_browser
15 {
16 namespace tools
17 {
18
19 template<typename T, typename R>
20 class WorkData {
21 public:
22     void setData(std::vector<T> data) {
23         this->data = data;
24     }
25     void setWorker(R (*worker)(T)) {
26         this->worker = worker;
27     }
28     T getNext() {
29         lock.lock();
30         if (data.size() == 0) {
31             lock.unlock();
32             throw std::exception();
33         } else {
34             T t = data.back();
35             data.pop_back();
36             lock.unlock();
37             return t;
38         }
39     }
40
41     void addResult(R r) {
42         boost::lock_guard<boost::mutex> lock(results_lock);
43         results.push_back(r);
44     }
45
46     std::vector<R> getResults() {
47         return results;
48     }
49
50     R executeWorker(T t) {
51         return worker(t);
52     }
53
54 private:
55     std::vector<T> data;
56     std::vector<R> results;
57     R (*worker)(T);
58     boost::mutex lock;
59     boost::mutex results_lock;
60 };
61
62 template<typename T, typename R>
63 class WorkQueue {
64 public:
65     WorkQueue(int threads) {
66         this->threadCount = threads;
67     }
68
69     void setWorker(R (*worker)(T)) {
70         this->workData.setWorker(worker);
71     }
72
73     void setData(std::vector<T> data) {
74         this->workData.setData(data);
75     }
76
77     std::vector<R> getResults() {
78         return this->workData.getResults();
79     }
80
81     void run() {
82         boost::thread taskThreads[threadCount];
83         for (int i = 0; i < threadCount; i++) {
84             taskThreads[i] = boost::thread(WorkQueue::threadWorker, &workData);
85         }
86         for (int i = 0; i < threadCount; i++) {
87             taskThreads[i].join();
88         }
89     }
90
91     static void threadWorker(WorkData<T, R>* workData) {
92         bool done = false;
93         while (done != true) {
94             try {
95                 T t = workData->getNext();
96                 R r = workData->executeWorker(t);
97                 workData->addResult(r);
98             } catch (std::exception& e) {
99                 done = true;
100             }
101         }
102     }
103
104 private:
105     WorkData<T, R> workData;
106     int threadCount;
107 };
108
109 template<typename T, typename R>
110 std::vector<R> parallel_for_each(std::vector<T> inputs, R (*func)(T)) {
111     tizen_browser::tools::WorkQueue<T, R> workQueue(4);
112     workQueue.setData(inputs);
113     workQueue.setWorker(func);
114     workQueue.run();
115     return workQueue.getResults();
116 }
117
118 }
119 }
120 #endif /* WORKQUEUE_H_ */