libosmscout 1.1.1
Loading...
Searching...
No Matches
AsyncWorker.h
Go to the documentation of this file.
1#ifndef LIBOSMSCOUT_ASYNCWORKER_H
2#define LIBOSMSCOUT_ASYNCWORKER_H
3
4/*
5 This source is part of the libosmscout library
6 Copyright (C) 2023 Lukas Karas
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22
24
28
29#include <thread>
30#include <cassert>
31
32namespace osmscout {
33
40 {
41 private:
42 osmscout::ProcessingQueue<std::function<void()>> queue;
43 bool deleteOnExit=false;
44
45 // thread have to be initialized after queue
46 std::thread thread;
47
48 public:
49 explicit AsyncWorker(const std::string &name);
50 virtual ~AsyncWorker();
51
52 AsyncWorker(const AsyncWorker&) = delete;
54
57
58 void Loop();
59
61
62 std::thread::id GetThreadId() const
63 {
64 return thread.get_id();
65 }
66
67 void ThreadAssert() const
68 {
69 assert(std::this_thread::get_id()==thread.get_id());
70 }
71
72 protected:
73 template<typename T>
74 CancelableFuture<T> Async(const std::function<T(Breaker&)> &task)
75 {
76 typename CancelableFuture<T>::Promise promise;
77 queue.PushTask([promise, task]() mutable {
78 typename CancelableFuture<T>::FutureBreaker breaker=promise.Breaker();
79 T result = task(breaker);
80 promise.SetValue(result);
81 });
82 return promise.Future();
83 }
84 };
85
86}
87
88#endif //LIBOSMSCOUT_ASYNCWORKER_H
#define OSMSCOUT_API
Definition CoreImportExport.h:45
AsyncWorker & operator=(const AsyncWorker &)=delete
AsyncWorker(const std::string &name)
AsyncWorker & operator=(AsyncWorker &&)=delete
void ThreadAssert() const
Definition AsyncWorker.h:67
std::thread::id GetThreadId() const
Definition AsyncWorker.h:62
AsyncWorker(const AsyncWorker &)=delete
AsyncWorker(AsyncWorker &&)=delete
CancelableFuture< T > Async(const std::function< T(Breaker &)> &task)
Definition AsyncWorker.h:74
Definition Breaker.h:37
Definition CancelableFuture.h:70
Definition CancelableFuture.h:109
void SetValue(const T &value)
Definition CancelableFuture.h:138
FutureBreaker Breaker() const
Definition CancelableFuture.h:150
CancelableFuture< T > Future() const
Definition CancelableFuture.h:123
Definition CancelableFuture.h:41
Definition ProcessingQueue.h:56
Definition Area.h:39