80 lines
2.8 KiB
C++
80 lines
2.8 KiB
C++
#ifndef PROCESS_PROCESS_COLLECTION_HPP
|
|
#define PROCESS_PROCESS_COLLECTION_HPP
|
|
|
|
#include <shared_mutex>
|
|
#include <functional>
|
|
|
|
#include <process/process.hpp>
|
|
#include <process/predicate.hpp>
|
|
|
|
namespace process::controller {
|
|
class ProcessDefinition;
|
|
/**
|
|
@TODO This collection holds up to N ProcessDefinitions with 0 or 1 Process created.
|
|
Each of N definition is unique by definition.
|
|
Todo: Check uniqueness of added definition!
|
|
Currently there is a scope lock inside for_each() function (because of maybe invalidated iter).
|
|
This blocks all concurrent action in all other threads.
|
|
ToDo: Reduce lock contention.
|
|
Proposal: Change vector to list. Do not remove an element from that list
|
|
in case the corresponding process has been stopped. Only insert at end of list.
|
|
Unless any element is deleted the collection is thread safe.
|
|
Use lock to get valid begin() and end() iterator only. Release lock afterwards
|
|
and iter through collection without lock.
|
|
*/
|
|
class ProcessCollection {
|
|
using create_process_fn = std::function<std::shared_ptr<Process>(
|
|
const process::controller::ProcessDefinition& pd)>;
|
|
|
|
public:
|
|
/// Initialize the create_process_for function with an own implementation
|
|
explicit ProcessCollection(create_process_fn create_process_for_f) noexcept(false);
|
|
|
|
ProcessCollection(create_process_fn create_process_for_f,
|
|
std::function<bool(const process::controller::ProcessDefinition)> predicate) noexcept(false);
|
|
|
|
/**
|
|
* Add a process using its definition.
|
|
*
|
|
* The definition gets passed to a predicate function deciding whether to
|
|
* accept it or not.
|
|
*
|
|
* @return true iff it was added to the collection, false otherwise
|
|
*/
|
|
void add(const process::controller::ProcessDefinition& definition);
|
|
|
|
/**
|
|
* Lookup a single process by its id.
|
|
*
|
|
* @return the process or null if it wasn't found
|
|
*/
|
|
std::shared_ptr<Process> get(const std::string& pd_id) const;
|
|
|
|
/**
|
|
* Iterate over all processes while holding the monitor lock.
|
|
*/
|
|
void for_each(const std::function<void(std::shared_ptr<Process>)>& pred) const;
|
|
|
|
/**
|
|
*
|
|
* @return the number of registered processes
|
|
*/
|
|
size_t size() const noexcept;
|
|
|
|
private:
|
|
/**
|
|
@return Searches and returns process with a given process definition ID. Nullptr if not found.
|
|
@param pd_id ID of process definition
|
|
@note Does not lock any mutex.
|
|
*/
|
|
std::shared_ptr<Process> lookup(const std::string& pd_id) const;
|
|
|
|
mutable std::shared_mutex m_mutex;
|
|
std::vector<std::shared_ptr<Process>> m_processes;
|
|
create_process_fn m_create_process;
|
|
|
|
std::function<bool(const process::controller::ProcessDefinition&)> m_predicate;
|
|
};
|
|
}
|
|
|
|
#endif
|