Lucene++ - a full-featured, c++ search engine
API Documentation

- Main Page
- Related Pages
- Namespaces
- Data Structures
- Files

- File List
- Globals

All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
ThreadPool.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2011 Alan Wright. All rights reserved.
3 // Distributable under the terms of either the Apache License (Version 2.0)
4 // or the GNU Lesser General Public License.
6
7 #ifndef THREADPOOL_H
8 #define THREADPOOL_H
9
10 #include <boost/asio.hpp>
11 #include <boost/any.hpp>
12 #include <boost/thread/thread.hpp>
13 #include "LuceneObject.h"
14
15 namespace Lucene
16 {
17 typedef boost::shared_ptr<boost::asio::io_service::work> workPtr;
18
22 class Future : public LuceneObject
23 {
24 public:
25 virtual ~Future();
26
27 protected:
28 boost::any value;
29
30 public:
31 void set(const boost::any& value)
32 {
33 SyncLock syncLock(this);
34 this->value = value;
35 }
36
37 template <typename TYPE>
38 TYPE get()
39 {
40 SyncLock syncLock(this);
41 while (value.empty())
42 wait(10);
43 return value.empty() ? TYPE() : boost::any_cast<TYPE>(value);
44 }
45 };
46
48 class ThreadPool : public LuceneObject
49 {
50 public:
51 ThreadPool();
52 virtual ~ThreadPool();
53
54 LUCENE_CLASS(ThreadPool);
55
56 protected:
57 boost::asio::io_service io_service;
58 workPtr work;
59 boost::thread_group threadGroup;
60
61 static const int32_t THREADPOOL_SIZE;
62
63 public:
65 static ThreadPoolPtr getInstance();
66
67 template <typename FUNC>
68 FuturePtr scheduleTask(FUNC func)
69 {
70 FuturePtr future(newInstance<Future>());
71 io_service.post(boost::bind(&ThreadPool::execute<FUNC>, this, func, future));
72 return future;
73 }
74
75 protected:
76 // this will be executed when one of the threads is available
77 template <typename FUNC>
78 void execute(FUNC func, FuturePtr future)
79 {
80 future->set(func());
81 future->notifyAll();
82 }
83 };
84 }
85
86 #endif

clucene.sourceforge.net