PetaVision  Alpha
Subject.cpp
1 /*
2  * Subject.cpp
3  *
4  * Created on: Jul 30, 2016
5  * Author: pschultz
6  */
7 
8 #include "observerpattern/Subject.hpp"
9 #include "utils/PVAssert.hpp"
10 #include "utils/PVLog.hpp"
11 #include <numeric>
12 
13 namespace PV {
14 
15 Response::Status Subject::notify(
16  ObserverTable const &table,
17  std::vector<std::shared_ptr<BaseMessage const>> messages,
18  bool printFlag) {
19  Response::Status returnStatus = Response::NO_ACTION;
20  auto &objectVector = table.getObjectVector();
21  std::vector<int> numPostponed(messages.size());
22  for (auto &obj : objectVector) {
23  for (int msgIdx = 0; msgIdx < messages.size(); msgIdx++) {
24  auto &msg = messages[msgIdx];
25  Response::Status status = obj->respond(msg);
26  returnStatus = returnStatus + status;
27 
28  // If an object postpones, skip any subsequent messages to that object.
29  // But continue onto the next object, in case it is what the postponing
30  // object is waiting for.
31  if (status == Response::POSTPONE) {
32  numPostponed[msgIdx]++;
33  if (printFlag) {
34  InfoLog().printf(
35  "%s postponed on %s.\n",
36  obj->getDescription_c(),
37  msg->getMessageType().c_str());
38  }
39  break;
40  }
41  }
42  }
43  if (printFlag) {
44  for (int msgIdx = 0; msgIdx < messages.size(); msgIdx++) {
45  int numPostponedThisMsg = numPostponed.at(msgIdx);
46  if (numPostponedThisMsg > 0) {
47  InfoLog().printf(
48  "%d objects postponed %s\n",
49  numPostponedThisMsg,
50  messages[msgIdx]->getMessageType().c_str());
51  }
52  }
53  }
54  return returnStatus;
55 }
56 
58  ObserverTable const &table,
59  std::vector<std::shared_ptr<BaseMessage const>> messages,
60  bool printFlag,
61  std::string const &description) {
62  Response::Status status = Response::PARTIAL;
63  while (status == Response::PARTIAL) {
64  status = notify(table, messages, printFlag);
65  }
66  FatalIf(
67  status == Response::POSTPONE,
68  "At least one object of %s postponed, but no object of %s progressed.\n",
69  description.c_str(),
70  description.c_str());
71  pvAssert(Response::completed(status));
72 }
73 
74 } /* namespace PV */
void notifyLoop(ObserverTable const &table, std::vector< std::shared_ptr< BaseMessage const >> messages, bool printFlag, std::string const &description)
Definition: Subject.cpp:57
static bool completed(Status &a)
Definition: Response.hpp:49
Response::Status notify(ObserverTable const &table, std::vector< std::shared_ptr< BaseMessage const >> messages, bool printFlag)
Definition: Subject.cpp:15