1717#ifndef VEHICLE_APP_SDK_JOB_H
1818#define VEHICLE_APP_SDK_JOB_H
1919
20+ #include < atomic>
2021#include < functional>
2122#include < memory>
2223#include < mutex>
2324
2425namespace velocitas {
2526
26- class ThreadPool ;
27- class IJob ;
28- using JobPtr_t = std::shared_ptr<IJob>;
29-
3027/* *
3128 * @brief Interface for jobs which can be executed by a worker in the thread pool.
32- *
3329 */
3430class IJob {
3531public:
@@ -38,59 +34,65 @@ class IJob {
3834
3935 /* *
4036 * @brief Execute the job.
37+ */
38+ virtual void execute () = 0;
39+
40+ /* *
41+ * @brief Indicates if this job shall recur after its execution.
4142 *
42- * @param thisJobPtr A smart pointer to this job. Allows sub classes to i.e. re-trigger the
43- * very same job instance.
44- * @param pool The pool that is executing the job. Allows sub classes to i.e.
45- * re-trigger the same job.
43+ * @return true - recur this job
44+ * @return false - don't recure
4645 */
47- virtual void execute (JobPtr_t& thisJobPtr, ThreadPool& pool) = 0; // NOLINT
46+ [[nodiscard]] virtual bool shallRecur () const { return false ; }
4847
4948 IJob (const IJob&) = delete ;
5049 IJob (IJob&&) = delete ;
5150 IJob& operator =(const IJob&) = delete ;
5251 IJob& operator =(IJob&&) = delete ;
5352};
5453
54+ using JobPtr_t = std::shared_ptr<IJob>;
55+
5556/* *
5657 * @brief A nonrecurring job.
57- *
5858 */
5959class Job : public IJob {
6060public:
6161 static JobPtr_t create (std::function<void ()> fun) { return std::make_shared<Job>(fun); }
6262
6363 explicit Job (std::function<void ()> fun);
6464
65- void execute (JobPtr_t& /* thisJobPtr*/ , ThreadPool& /* pool*/ ) override ;
66-
67- std::function<void ()> getFunction () { return m_fun; }
65+ void execute () override ;
6866
69- void waitForTermination ();
67+ void waitForTermination () const ;
7068
7169private:
7270 std::function<void ()> m_fun;
73- std::mutex m_terminationMutex;
71+ mutable std::mutex m_terminationMutex;
7472};
7573
7674/* *
7775 * @brief A recurring job which can be cancelled manually.
78- *
7976 */
8077class RecurringJob : public Job {
8178public:
8279 static JobPtr_t create (std::function<void ()> fun) {
8380 return std::make_shared<RecurringJob>(fun);
8481 }
8582
86- void execute (JobPtr_t& thisJobPtr, ThreadPool& pool) override ;
83+ using Job::Job;
84+
85+ void execute () override ;
8786
87+ /* *
88+ * @brief Prevents execution of the function once called.
89+ */
8890 void cancel () { m_isCancelled = true ; }
8991
90- using Job::Job;
92+ [[nodiscard]] bool shallRecur () const override { return !m_isCancelled; }
9193
9294private:
93- bool m_isCancelled{false };
95+ std::atomic_bool m_isCancelled{false };
9496};
9597
9698} // namespace velocitas
0 commit comments