Program Listing for File concurrence.hpp

Return to documentation for file (include/yasmin/concurrence.hpp)

// Copyright (C) 2025 Georgia Tech Research Institute
// Supported by USDA-NIFA CSIAPP Grant. No. 2023-70442-39232
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef YASMIN__CONCURRENCE_HPP
#define YASMIN__CONCURRENCE_HPP

#include <atomic>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <vector>

#ifdef __GNUG__     // If using GCC/G++
#include <cxxabi.h> // For abi::__cxa_demangle
#endif

#include "yasmin/blackboard/blackboard.hpp"
#include "yasmin/state.hpp"

namespace yasmin {

class Concurrence : public State {

public:
  typedef std::map<std::shared_ptr<State>, std::string> StateMap;
  typedef std::map<std::string, StateMap> OutcomeMap;

protected:
  const std::set<std::shared_ptr<State>> states;

  const std::string default_outcome;

  OutcomeMap outcome_map;

  std::map<std::shared_ptr<State>, std::shared_ptr<std::string>>
      intermediate_outcome_map;

  std::set<std::string> possible_outcomes;

private:
  std::mutex intermediate_outcome_mutex;

  static std::set<std::string>
  generate_possible_outcomes(const OutcomeMap &outcome_map,
                             const std::string &default_outcome);

public:
  Concurrence(std::set<std::shared_ptr<State>> states,
              std::string default_outcome, OutcomeMap outcome_map);

  std::string
  execute(std::shared_ptr<blackboard::Blackboard> blackboard) override;

  void cancel_state() override;

  std::string to_string() override {
    std::string name = typeid(*this).name();

#ifdef __GNUG__ // If using GCC/G++
    int status;
    // Demangle the name using GCC's demangling function
    char *demangled =
        abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status);
    if (status == 0) {
      name = demangled;
    }
    free(demangled);
#endif

    name += "[";

    for (auto it = states.begin(); it != states.end(); ++it) {
      name += (*it)->to_string();

      // Add a comma if this is not the last element
      if (std::next(it) != states.end()) {
        name += ", ";
      }
    }

    name += "]";

    return name; // Return the demangled class name
  }
};

} // namespace yasmin

#endif // YASMIN__CONCURRENCE_HPP