Line data Source code
1 : /* 2 : * This file is part of PTN Engine 3 : * 4 : * Copyright (c) 2023-2024 Eduardo ValgĂ´de 5 : * 6 : * Licensed under the Apache License, Version 2.0 (the "License"); 7 : * you may not use this file except in compliance with the License. 8 : * You may obtain a copy of the License at 9 : * 10 : * http://www.apache.org/licenses/LICENSE-2.0 11 : * 12 : * Unless required by applicable law or agreed to in writing, software 13 : * distributed under the License is distributed on an "AS IS" BASIS, 14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 : * See the License for the specific language governing permissions and 16 : * limitations under the License. 17 : */ 18 : 19 : #include "PTN_Engine/JobQueue/JobQueue.h" 20 : #include <thread> 21 : 22 : namespace ptne 23 : { 24 : using namespace std; 25 : 26 64 : JobQueue::JobQueue() = default; 27 : 28 : //! The thread destructor will request to stop and then join, by default. 29 64 : JobQueue::~JobQueue() = default; 30 : 31 2 : void JobQueue::activate() 32 : { 33 2 : if (m_isJobQueueActive) 34 : { 35 0 : return; 36 : } 37 2 : m_isJobQueueActive = true; 38 2 : launch(); 39 : } 40 : 41 2 : void JobQueue::deactivate() noexcept 42 : { 43 2 : if (!m_isJobQueueActive) 44 : { 45 0 : return; 46 : } 47 2 : if (m_workerThread.get_stop_token().stop_possible()) 48 : { 49 0 : m_workerThread.request_stop(); 50 0 : m_workerThread.join(); 51 : } 52 2 : m_isJobQueueActive = false; 53 : } 54 : 55 7 : bool JobQueue::isActive() const 56 : { 57 7 : return m_isJobQueueActive; 58 : } 59 : 60 200009 : void JobQueue::launch() 61 : { 62 200009 : lock_guard l(m_jobQueueMutex); 63 200009 : if (!m_isJobQueueRunning && !m_jobQueue.empty() && m_isJobQueueActive) 64 : { 65 194392 : m_isJobQueueRunning = true; 66 : try 67 : { 68 194392 : m_workerThread = jthread(bind_front(&JobQueue::run, this)); 69 : } 70 0 : catch (const std::system_error &) 71 : { 72 0 : m_isJobQueueRunning = false; 73 0 : } 74 : } 75 200009 : } 76 : 77 194392 : void JobQueue::run(stop_token stopToken) 78 : { 79 194392 : unique_lock l(m_jobQueueMutex); 80 394399 : while (!m_jobQueue.empty() && !stopToken.stop_requested()) 81 : { 82 200007 : ActionFunction job = m_jobQueue.back(); 83 200007 : m_jobQueue.pop_back(); 84 200007 : l.unlock(); 85 200007 : job(); 86 200007 : l.lock(); 87 200007 : } 88 194392 : m_isJobQueueRunning = false; 89 194392 : } 90 : 91 200007 : void JobQueue::addJob(const ActionFunction &actionFunction) 92 : { 93 : { 94 200007 : lock_guard l(m_jobQueueMutex); 95 200007 : m_jobQueue.push_front(actionFunction); 96 200007 : } 97 200007 : launch(); 98 200007 : } 99 : 100 : } // namespace ptne