Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
5 : * This Source Code Form is subject to the terms of the Mozilla Public
6 : * License, v. 2.0. If a copy of the MPL was not distributed with this
7 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 : */
9 :
10 : #ifndef INCLUDED_COMPHELPER_THREADPOOL_HXX
11 : #define INCLUDED_COMPHELPER_THREADPOOL_HXX
12 :
13 : #include <sal/config.h>
14 : #include <salhelper/thread.hxx>
15 : #include <osl/mutex.hxx>
16 : #include <osl/conditn.hxx>
17 : #include <rtl/ref.hxx>
18 : #include <vector>
19 : #include <comphelper/comphelperdllapi.h>
20 :
21 : namespace comphelper
22 : {
23 :
24 3382 : class COMPHELPER_DLLPUBLIC ThreadTask
25 : {
26 : public:
27 3379 : virtual ~ThreadTask() {}
28 : virtual void doWork() = 0;
29 : };
30 :
31 : /// A very basic thread pool implementation
32 : class COMPHELPER_DLLPUBLIC ThreadPool
33 : {
34 : public:
35 : /// returns a pointer to a shared pool with optimal thread
36 : /// count for the CPU
37 : static ThreadPool& getSharedOptimalPool();
38 :
39 : ThreadPool( sal_Int32 nWorkers );
40 : virtual ~ThreadPool();
41 :
42 : /// push a new task onto the work queue
43 : void pushTask( ThreadTask *pTask /* takes ownership */ );
44 :
45 : /// wait until all queued tasks are completed
46 : void waitUntilEmpty();
47 :
48 : /// return the number of live worker threads
49 99 : sal_Int32 getWorkerCount() const { return maWorkers.size(); }
50 :
51 : private:
52 : ThreadPool(const ThreadPool&) SAL_DELETED_FUNCTION;
53 : ThreadPool& operator=(const ThreadPool&) SAL_DELETED_FUNCTION;
54 :
55 : class ThreadWorker;
56 : friend class ThreadWorker;
57 :
58 : /// wait until all work is completed, then join all threads
59 : void waitAndCleanupWorkers();
60 :
61 : ThreadTask *waitForWork( osl::Condition &rNewWork );
62 : ThreadTask *popWork();
63 : void startWork();
64 : void stopWork();
65 :
66 : osl::Mutex maGuard;
67 : sal_Int32 mnThreadsWorking;
68 : /// signalled when all in-progress tasks are complete
69 : osl::Condition maTasksComplete;
70 : bool mbTerminate;
71 : std::vector< rtl::Reference< ThreadWorker > > maWorkers;
72 : std::vector< ThreadTask * > maTasks;
73 : };
74 :
75 : } // namespace comphelper
76 :
77 : #endif // INCLUDED_COMPHELPER_THREADPOOL_HXX
78 :
79 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|