diff --git a/plugins/pyloader/src/plugin.cc b/plugins/pyloader/src/plugin.cc index 297d656..b864a6f 100644 --- a/plugins/pyloader/src/plugin.cc +++ b/plugins/pyloader/src/plugin.cc @@ -26,29 +26,29 @@ using namespace sgpem; // Is this OK? If not, we must use a function with a local static variable... -PythonCPUPolicyManager* _policy_manager = NULL; +PythonCPUPolicyManager* _policy_manager = NULL; -void +void sgpem__Plugin__on_init() { - if(_policy_manager == NULL) + if (_policy_manager == NULL) _policy_manager = new sgpem::PythonCPUPolicyManager(); } -void +void sgpem__Plugin__on_exit() { delete _policy_manager; _policy_manager = NULL; } -const char* +const char* sgpem__Plugin__describe() { return "This plugin manages policies written in the Python scripting language"; } -const char* +const char* sgpem__Plugin__get_name() { return "Pyloader"; diff --git a/plugins/pyloader/src/python_cpu_policy.cc b/plugins/pyloader/src/python_cpu_policy.cc index b9bbb19..d9e86e9 100644 --- a/plugins/pyloader/src/python_cpu_policy.cc +++ b/plugins/pyloader/src/python_cpu_policy.cc @@ -39,9 +39,9 @@ PythonCPUPolicy::PythonCPUPolicy(const char* name) throw(MalformedPolicyExceptio PyObject* pUserCPUPolicyModule = PyImport_Import(pLoadmeStr); Py_DECREF(pLoadmeStr); - if(pUserCPUPolicyModule == NULL) + if (pUserCPUPolicyModule == NULL) throw MalformedPolicyException(get_exception_information().c_str()); - + // Dictionary with defined ``symbols'' for .pyc file _upolicy_dict = PyModule_GetDict(pUserCPUPolicyModule); assert(_upolicy_dict); @@ -66,24 +66,24 @@ PythonCPUPolicy::PythonCPUPolicy(const char* name) throw(MalformedPolicyExceptio PyTuple_SetItem(pAdapterCtorParam, 0, pCPUPolicyClass); _adapter = PyInstance_New(pAdapterClass, pAdapterCtorParam, NULL); Py_DECREF(pAdapterCtorParam); - + Py_DECREF(pScriptAdapterModule); - - if(_adapter == NULL) + + if (_adapter == NULL) throw MalformedPolicyException(get_exception_information().c_str()); - + // And now, who's your daddy, huh? } PythonCPUPolicy::~PythonCPUPolicy() { - if(_adapter) Py_DECREF(_adapter); + if (_adapter) Py_DECREF(_adapter); // We keep this alive until dtor time, because // the user may have defined some static global-space // variables and they make use of them. - if(_upolicy_dict) Py_DECREF(_upolicy_dict); + if (_upolicy_dict) Py_DECREF(_upolicy_dict); } void @@ -122,7 +122,7 @@ PythonCPUPolicy::sort_queue() const throw(UserInterruptException) PyObject* retval = PyObject_CallMethod(_adapter, "async_sort_queue", NULL); // Do minimal debugging - if(!retval) PyErr_Print(); + if (!retval) PyErr_Print(); else Py_DECREF(retval); wait_unlock(); @@ -163,9 +163,9 @@ int PythonCPUPolicy::get_time_slice() const throw(UserInterruptException) { PyObject* retval = PyObject_CallMethod(_adapter, "async_get_time_slice", NULL); - + // Do minimal debugging - if(!retval) PyErr_Print(); + if (!retval) PyErr_Print(); else Py_DECREF(retval); wait_unlock(); @@ -193,13 +193,13 @@ PythonCPUPolicy::wait_unlock() const throw(UserInterruptException) Py_UNBLOCK_THREADS; usleep(WAIT_FOR); // hack'a'ton! magggggiccc nummmbeeerrrrrs!! Py_BLOCK_THREADS; - + PyObject* retval = PyObject_CallMethod(_adapter, "mutex_test_lock", NULL); assert(retval); still_locked = PyObject_IsTrue(retval); Py_DECREF(retval); - if(i++ > 12) /* waits for WAIT_FOR * 12 microseconds == 3 secs */ + if (i++ > 12) /* waits for WAIT_FOR * 12 microseconds == 3 secs */ { PyThreadState_Clear(_save); // As the API documentation says, the caller of PyEval_RestoreThread @@ -209,10 +209,10 @@ PythonCPUPolicy::wait_unlock() const throw(UserInterruptException) throw UserInterruptException(_("User-defined policy is " - "taking too long to terminate.")); + "taking too long to terminate.")); } } - while(still_locked); + while (still_locked); // What we should really do here: /* do { @@ -234,9 +234,9 @@ PythonCPUPolicy::wait_unlock() const throw(UserInterruptException) string PythonCPUPolicy::get_exception_information() { - if(PyErr_Occurred() == NULL) + if (PyErr_Occurred() == NULL) return _("no error"); - + PyObject* pType = NULL; PyObject* pValue = NULL; PyObject* pTraceback = NULL; @@ -245,7 +245,7 @@ PythonCPUPolicy::get_exception_information() string msg; - if(pValue != NULL) + if (pValue != NULL) { PyObject* pValueStr = PyObject_Str(pValue); @@ -256,9 +256,9 @@ PythonCPUPolicy::get_exception_information() else msg = string(_("no available information for this error")); - if(pType != NULL) Py_DECREF(pType); - if(pValue != NULL) Py_DECREF(pValue); - if(pTraceback != NULL) Py_DECREF(pTraceback); + if (pType != NULL) Py_DECREF(pType); + if (pValue != NULL) Py_DECREF(pValue); + if (pTraceback != NULL) Py_DECREF(pTraceback); return msg; } diff --git a/plugins/pyloader/src/python_cpu_policy_manager.cc b/plugins/pyloader/src/python_cpu_policy_manager.cc index b34183c..56f9aa5 100644 --- a/plugins/pyloader/src/python_cpu_policy_manager.cc +++ b/plugins/pyloader/src/python_cpu_policy_manager.cc @@ -74,7 +74,7 @@ PythonCPUPolicyManager::~PythonCPUPolicyManager() void PythonCPUPolicyManager::init() { - if(_initialized) + if (_initialized) // No-op return; @@ -114,35 +114,35 @@ PythonCPUPolicyManager::collect_policies() GlobalPreferences::dir_iterator dir_it = prefs.policies_dir_begin(); GlobalPreferences::dir_iterator dir_end = prefs.policies_dir_end(); - for(; dir_it != dir_end; ++dir_it) + for (; dir_it != dir_end; ++dir_it) { Glib::Dir dir(dir_it->c_str()); cout << "Opening directory " << *dir_it << " looking for python policies..." << endl; - for(Glib::DirIterator file_it = dir.begin(); file_it != dir.end(); ++file_it) + for (Glib::DirIterator file_it = dir.begin(); file_it != dir.end(); ++file_it) { cout << "\tChecking if " << *file_it << " is a valid Python script... "; Glib::PatternSpec dot_py("*.py"); - if(dot_py.match(*file_it)) + if (dot_py.match(*file_it)) { - cout << "yes" << endl; - + cout << "yes" << endl; + //strip extension std::string policy_name = (*file_it).substr(0, (*file_it).size() - 3); try - { - PythonCPUPolicy *pypolicy = new PythonCPUPolicy(policy_name.c_str()); + { + PythonCPUPolicy *pypolicy = new PythonCPUPolicy(policy_name.c_str()); - _policies.push_back(pypolicy); - } - catch(MalformedPolicyException e) - { - std::cerr << "POLICY LOAD ERROR: " << e.what() << endl; - } + _policies.push_back(pypolicy); + } + catch (MalformedPolicyException e) + { + std::cerr << "POLICY LOAD ERROR: " << e.what() << endl; + } } else cout << "no" << endl; diff --git a/plugins/pyloader/src/python_cpu_policy_manager.hh b/plugins/pyloader/src/python_cpu_policy_manager.hh index ccbd726..0aafba6 100644 --- a/plugins/pyloader/src/python_cpu_policy_manager.hh +++ b/plugins/pyloader/src/python_cpu_policy_manager.hh @@ -57,7 +57,7 @@ namespace sgpem /** The selected and active PyhonCPUPolicy object. */ void collect_policies(); - private: + private: PythonCPUPolicyManager(const PythonCPUPolicyManager&); PythonCPUPolicyManager& operator=(const PythonCPUPolicyManager&); diff --git a/plugins/pyloader/src/testsuite/test-python_loader.cc b/plugins/pyloader/src/testsuite/test-python_loader.cc index 7a5c6b4..e826cfe 100644 --- a/plugins/pyloader/src/testsuite/test-python_loader.cc +++ b/plugins/pyloader/src/testsuite/test-python_loader.cc @@ -45,11 +45,11 @@ using namespace std; static CPUPolicy* find_pol_by_name(const vector& pols, const Glib::ustring& name) { - vector::const_iterator it = pols.begin(); - for( ; it != pols.end(); it++) - if((*it)->get_name() == name) - return *it; - return NULL; + vector::const_iterator it = pols.begin(); + for ( ; it != pols.end(); it++) + if ((*it)->get_name() == name) + return *it; + return NULL; } @@ -58,7 +58,7 @@ main(int argc, char** argv) { int successes = 0; - if(argc != 2) + if (argc != 2) { std::cout << "[EE] Usage:\n\t" << argv[0] << " path/to/uninstalled/test/policies" << std::endl; @@ -72,29 +72,29 @@ main(int argc, char** argv) PythonCPUPolicyManager polman; polman.init(); - Simulation& sim = Simulation::get_instance(); - History& his = sim.get_history(); - CPUPoliciesGatekeeper& pgk = CPUPoliciesGatekeeper::get_instance(); + Simulation& sim = Simulation::get_instance(); + History& his = sim.get_history(); + CPUPoliciesGatekeeper& pgk = CPUPoliciesGatekeeper::get_instance(); - const std::vector& policies = polman.get_avail_policies(); + const std::vector& policies = polman.get_avail_policies(); - // Print out avail policies - cout << "These are the policies I found:" << endl; - vector::const_iterator it = policies.begin(); - for(; it != policies.end(); it++) - cout << "\t * " << (*it)->get_name() << endl; + // Print out avail policies + cout << "These are the policies I found:" << endl; + vector::const_iterator it = policies.begin(); + for (; it != policies.end(); it++) + cout << "\t * " << (*it)->get_name() << endl; try { - CPUPolicy* pol = find_pol_by_name(policies, "python_loader_configure"); - assert(pol != NULL); + CPUPolicy* pol = find_pol_by_name(policies, "python_loader_configure"); + assert(pol != NULL); - // FIXME : Maybe activating a policy only to configure it is an overkill? - // Who gives a fuck about it? + // FIXME : Maybe activating a policy only to configure it is an overkill? + // Who gives a fuck about it? pgk.activate_policy(&his, pol); pol->configure(); } - catch(UserInterruptException e) + catch (UserInterruptException e) { cout << "configure: Caught UserInterruptException" << endl; successes++; @@ -103,12 +103,12 @@ main(int argc, char** argv) try { - CPUPolicy* pol = find_pol_by_name(policies, "python_loader_is_preemptive"); - assert(pol != NULL); + CPUPolicy* pol = find_pol_by_name(policies, "python_loader_is_preemptive"); + assert(pol != NULL); pgk.activate_policy(&his, pol); pol->is_pre_emptive(); } - catch(UserInterruptException e) + catch (UserInterruptException e) { cout << "is_preemptive: Caught UserInterruptException" << endl; successes++; @@ -117,12 +117,12 @@ main(int argc, char** argv) try { - CPUPolicy* pol = find_pol_by_name(policies, "python_loader_get_time_slice"); - assert(pol != NULL); + CPUPolicy* pol = find_pol_by_name(policies, "python_loader_get_time_slice"); + assert(pol != NULL); pgk.activate_policy(&his, pol); pol->get_time_slice(); } - catch(UserInterruptException e) + catch (UserInterruptException e) { cout << "get_time_slice: Caught UserInterruptException" << endl; successes++; @@ -132,12 +132,12 @@ main(int argc, char** argv) try { - CPUPolicy* pol = find_pol_by_name(policies, "python_loader_get_time_slice"); - assert(pol != NULL); + CPUPolicy* pol = find_pol_by_name(policies, "python_loader_get_time_slice"); + assert(pol != NULL); pgk.activate_policy(&his, pol); pol->sort_queue(); } - catch(UserInterruptException e) + catch (UserInterruptException e) { cout << "sort_queue: Caught UserInterruptException" << endl; successes++; diff --git a/plugins/xmlsave/src/plugin.cc b/plugins/xmlsave/src/plugin.cc index e5a421e..10d473d 100644 --- a/plugins/xmlsave/src/plugin.cc +++ b/plugins/xmlsave/src/plugin.cc @@ -27,27 +27,27 @@ using namespace sgpem; sgpem::XMLSerializer* _serializer = NULL; -void +void sgpem__Plugin__on_init() { - if(_serializer == NULL) + if (_serializer == NULL) _serializer = new sgpem::XMLSerializer(); } -void +void sgpem__Plugin__on_exit() { delete _serializer; _serializer = NULL; } -const char* +const char* sgpem__Plugin__describe() { return "This plugin saves the simulation to an XML file"; } -const char* +const char* sgpem__Plugin__get_name() { return "XmlSave"; diff --git a/plugins/xmlsave/src/testsuite/test-xml_serializer.cc b/plugins/xmlsave/src/testsuite/test-xml_serializer.cc index fee1f66..79fe391 100644 --- a/plugins/xmlsave/src/testsuite/test-xml_serializer.cc +++ b/plugins/xmlsave/src/testsuite/test-xml_serializer.cc @@ -42,7 +42,7 @@ using namespace std; /* * This program tests the XML serialization via the XMLSerializer class. - * + * */ @@ -62,13 +62,13 @@ main(int argc, char** argv) { // output file name Glib::ustring outfile("xml-visit.xml"); - + // string stream to compare print dump of environment ostringstream os1; ostringstream os2; ostringstream os3; ostringstream os4; - + ConcreteHistory hist; cout << "create ConcreteHistory hist" << endl; @@ -90,38 +90,38 @@ main(int argc, char** argv) // add something other to history addSomethingHistory(hist); cout << "add other data to hist" << endl; - + // print on a string stream os2 dumpEnvironment(hist.get_last_environment(), os2); os2 << ends; // null terminated string cout << "dump hist(t2) in print format into os2" << endl; - - cout << "Comparing dump of hist(t1) and hist(t2): " << (os1.str()==os2.str()?"equals":"not equals") << endl; + + cout << "Comparing dump of hist(t1) and hist(t2): " << (os1.str() == os2.str() ? "equals" : "not equals") << endl; ConcreteHistory hist2; xmlser.restore_snapshot(outfile, hist2); cout << "create ConcreteHistory hist" << endl; - cout << "read XML data from file " << outfile << " and put into hist2(t3)"<< endl; + cout << "read XML data from file " << outfile << " and put into hist2(t3)" << endl; dumpEnvironment(hist2.get_last_environment(), os3); os3 << ends; // null terminated string cout << "dump hist2(t3) in print format into os3" << endl; - - cout << "Comparing dump of hist(t1) and hist2(t3): " << (os1.str()==os3.str()?"equals":"not equals") << endl; + + cout << "Comparing dump of hist(t1) and hist2(t3): " << (os1.str() == os3.str() ? "equals" : "not equals") << endl; xmlser.restore_snapshot(outfile, hist); - cout << "read XML data from file " << outfile << " and put into hist(t4)"<< endl; - + cout << "read XML data from file " << outfile << " and put into hist(t4)" << endl; + dumpEnvironment(hist.get_last_environment(), os4); os4 << ends; // null terminated string cout << "dump hist(t3) in print format into os4" << endl; - - cout << "Comparing dump of hist(t1) and hist(t4): " << (os1.str()==os4.str()?"equals":"not equals") << endl; - + + cout << "Comparing dump of hist(t1) and hist(t4): " << (os1.str() == os4.str() ? "equals" : "not equals") << endl; + int ret = 1; - if(os1.str()!=os2.str() - && os1.str()==os3.str() - && os1.str()==os4.str()) + if (os1.str() != os2.str() + && os1.str() == os3.str() + && os1.str() == os4.str()) { cout << "test successful" << endl; ret = 0; @@ -131,7 +131,7 @@ main(int argc, char** argv) cout << "test failed" << endl; ret = 1; } - return ret; + return ret; } @@ -145,10 +145,10 @@ void fillHistory(History &hist) History::ResourcePair respair0 = hist.add_resource(Glib::ustring("Resource 0"), false, 1, 2); // add a resource - name, preemptable, places, availability History::ResourcePair respair00 = hist.add_resource(Glib::ustring("Resource 00"), false, 1, 2); - + // add a resource - name, preemptable, places, availability History::ResourcePair respair = hist.add_resource(Glib::ustring("Resource 1"), false, 1, 2); - + // add a resource - name, preemptable, places, availability History::ResourcePair respair2 = hist.add_resource(Glib::ustring("Invalid? Resource 1"), false, 1, 2); // and print his values @@ -201,32 +201,32 @@ void addSomethingHistory(History &hist) // print entire environment into the passed ostream void dumpEnvironment(const Environment& env, ostream &os) { - os << "dump environment start " <get_name() - /* << " key: " << (*riter).first */ - << " places: " << r->get_places() << endl; + /* << " key: " << (*riter).first */ + << " places: " << r->get_places() << endl; riter++; } - + const Environment::Processes& pvect = env.get_processes(); typedef std::vector::const_iterator proc_iterator; proc_iterator iter = pvect.begin(); proc_iterator end = pvect.end(); - while(iter!=end) + while (iter != end) { Process* p = (*iter); os << " process name: " << p->get_name() - << " arrival_time: " << p->get_arrival_time() - << " base_priority: " << p->get_base_priority() << endl; + << " arrival_time: " << p->get_arrival_time() + << " base_priority: " << p->get_base_priority() << endl; iter++; typedef std::vector Threads; @@ -234,20 +234,20 @@ void dumpEnvironment(const Environment& env, ostream &os) const Threads& tvect = p->get_threads(); thr_iterator iter1 = tvect.begin(); thr_iterator end1 = tvect.end(); - while(iter1!=end1) + while (iter1 != end1) { Thread* t = (*iter1); os << " thread name: " << t->get_name() - << " arrival_time: " << t->get_arrival_time() - << " base_priority: " << t->get_base_priority() << endl; + << " arrival_time: " << t->get_arrival_time() + << " base_priority: " << t->get_base_priority() << endl; typedef std::vector Requests; typedef std::vector::const_iterator req_iterator; const Requests& rvect = t->get_requests(); req_iterator iter2 = rvect.begin(); req_iterator end2 = rvect.end(); - while(iter2!=end2) + while (iter2 != end2) { Request* r = (*iter2); @@ -258,14 +258,15 @@ void dumpEnvironment(const Environment& env, ostream &os) const SubRequests& srvect = r->get_subrequests(); subreq_iterator iter3 = srvect.begin(); subreq_iterator end3 = srvect.end(); - while(iter3!=end3) + while (iter3 != end3) { SubRequest* sr = (*iter3); os << " sub request: " /* << " resource_key: " << sr->get_resource_key() */; - + Environment::Resources::const_iterator pos = env.get_resources().find(sr->get_resource_key()); - if (pos != env.get_resources().end()) { + if (pos != env.get_resources().end()) + { os << " name: " << pos->second->get_name(); } diff --git a/plugins/xmlsave/src/xml_serializer.cc b/plugins/xmlsave/src/xml_serializer.cc index bccefb5..651c940 100644 --- a/plugins/xmlsave/src/xml_serializer.cc +++ b/plugins/xmlsave/src/xml_serializer.cc @@ -31,12 +31,10 @@ using namespace sgpem; XMLSerializer::~XMLSerializer() -{ -} +{} XMLSerializer::XMLSerializer() -{ -} +{} @@ -45,13 +43,14 @@ void XMLSerializer::save_snapshot(const Glib::ustring& filename, const History& /* COMPAT: Do not genrate nodes for formatting spaces */ LIBXML_TEST_VERSION xmlKeepBlanksDefault(0); - + xmlDocPtr doc; doc = xmlNewDoc((const xmlChar *)"1.0"); - if(doc!=NULL){ + if (doc != NULL) + { fill_doc(doc, hist); int nwritten = xmlSaveFormatFile (filename.c_str(), doc, 1); - if(nwritten<0) + if (nwritten < 0) { throw SerializerError("Error writing xml doc to output stream."); } @@ -60,48 +59,49 @@ void XMLSerializer::save_snapshot(const Glib::ustring& filename, const History& { throw SerializerError("Internal Error creating xml doc."); } - + /* Clean up everything else before quitting. */ xmlCleanupParser(); } void XMLSerializer::restore_snapshot(const Glib::ustring& filename, History& hist) throw(SerializerError) { - // TODO - all to do!! - // DEBUG - remove me when finished + // TODO - all to do!! + // DEBUG - remove me when finished #ifdef LIBXML_SAX1_ENABLED - xmlDocPtr doc; - - LIBXML_TEST_VERSION - xmlKeepBlanksDefault(0); + xmlDocPtr doc; - /* - * build an XML tree from a the file; - */ - doc = xmlParseFile(filename.c_str()); - if (doc == NULL) { - xmlCleanupParser(); - throw SerializerError("Parsing Error: doc is invalid."); - } + LIBXML_TEST_VERSION + xmlKeepBlanksDefault(0); - clear_history(hist); - XMLSerializerFactory fact(hist); - - // read all elements and fill hist - read_doc(doc, fact); - - // frees all xml related data - xmlFreeDoc(doc); - - /* Clean up everything else before quitting. */ + /* + * build an XML tree from a the file; + */ + doc = xmlParseFile(filename.c_str()); + if (doc == NULL) + { xmlCleanupParser(); + throw SerializerError("Parsing Error: doc is invalid."); + } + + clear_history(hist); + XMLSerializerFactory fact(hist); + + // read all elements and fill hist + read_doc(doc, fact); + + // frees all xml related data + xmlFreeDoc(doc); + + /* Clean up everything else before quitting. */ + xmlCleanupParser(); #else - /* - * the library has been compiled without some of the old interfaces - */ - #error Compilation of LIBXML with SAX1 support must be enabled + /* + * the library has been compiled without some of the old interfaces + */ +#error Compilation of LIBXML with SAX1 support must be enabled #endif /* LIBXML_SAX1_ENABLED */ } @@ -112,57 +112,57 @@ void XMLSerializer::restore_snapshot(const Glib::ustring& filename, History& his const Glib::ustring XMLSerializer::get_filename_extension() { - return Glib::ustring("xsgp"); + return Glib::ustring("xsgp"); } const Glib::ustring XMLSerializer::get_filename_description() { - return Glib::ustring("SGPEMv2 XML savefile"); + return Glib::ustring("SGPEMv2 XML savefile"); } void XMLSerializer::fill_doc(xmlDocPtr doc, const History& hist) { - xmlNodePtr root_node = NULL;/* node pointers */ - /* - * Creates a new document, a node and set it as a root node - */ - root_node = xmlNewNode(NULL, (const xmlChar *) "sgpem"); - xmlDocSetRootElement(doc, root_node); + xmlNodePtr root_node = NULL;/* node pointers */ + /* + * Creates a new document, a node and set it as a root node + */ + root_node = xmlNewNode(NULL, (const xmlChar *) "sgpem"); + xmlDocSetRootElement(doc, root_node); - /* - * Creates a DTD declaration. Isn't mandatory. - */ - xmlDtdPtr dtd = xmlCreateIntSubset(doc, (const xmlChar *) "sgpem", NULL, (const xmlChar *) "sgpem.dtd"); + /* + * Creates a DTD declaration. Isn't mandatory. + */ + xmlDtdPtr dtd = xmlCreateIntSubset(doc, (const xmlChar *) "sgpem", NULL, (const xmlChar *) "sgpem.dtd"); - XMLVisitor xvisit(root_node); - xvisit.from_history(hist); - /* - // - // xmlNewChild() creates a new node, which is "attached" as child node - // of root_node node. - // - xmlNodePtr resources_node = xmlNewChild(root_node, NULL, (const xmlChar *) "resources", NULL); - // - // The same as above, but the new child node doesn't have a content - // - xmlNodePtr schedulables_node = xmlNewChild(root_node, NULL, (const xmlChar *) "schedulables", NULL); + XMLVisitor xvisit(root_node); + xvisit.from_history(hist); + /* + // + // xmlNewChild() creates a new node, which is "attached" as child node + // of root_node node. + // + xmlNodePtr resources_node = xmlNewChild(root_node, NULL, (const xmlChar *) "resources", NULL); + // + // The same as above, but the new child node doesn't have a content + // + xmlNodePtr schedulables_node = xmlNewChild(root_node, NULL, (const xmlChar *) "schedulables", NULL); - fill_resources(resources_node, hist); - fill_schedulables(schedulables_node, hist); - */ + fill_resources(resources_node, hist); + fill_schedulables(schedulables_node, hist); + */ } /* void XMLSerializer::fill_resources(xmlNodePtr resources_node, const History& hist) { - + const Environment& env = hist.get_last_environment(); const Environment::Resources& rvect = env.get_resources(); typedef Environment::Resources::const_iterator res_iterator; - + res_iterator iter = rvect.begin(); res_iterator end = rvect.end(); while(iter!=end) @@ -177,13 +177,13 @@ void XMLSerializer::fill_resources(xmlNodePtr resources_node, const History& his void XMLSerializer::fill_schedulables(xmlNodePtr schedulables_node, const History& hist) { - + const Environment& env = hist.get_last_environment(); const Environment::Processes& pvect = env.get_processes(); typedef std::vector::const_iterator proc_iterator; - + proc_iterator iter = pvect.begin(); proc_iterator end = pvect.end(); while(iter!=end) @@ -198,71 +198,74 @@ void XMLSerializer::fill_schedulables(xmlNodePtr schedulables_node, const Histor void XMLSerializer::clear_history(History& hist) { - const Environment& env = hist.get_last_environment(); + const Environment& env = hist.get_last_environment(); - const Environment::Processes& pvect = env.get_processes(); - typedef std::vector::const_iterator proc_iterator; - - proc_iterator iter = pvect.begin(); - while(iter!=pvect.end()) - { - hist.remove(*(*iter)); - iter = pvect.begin(); - } + const Environment::Processes& pvect = env.get_processes(); + typedef std::vector::const_iterator proc_iterator; - const Environment::Resources& rvect = env.get_resources(); - typedef Environment::Resources::const_iterator res_iterator; - - res_iterator riter = rvect.begin(); - while(riter!=rvect.end()) - { - hist.remove((*riter).first); - riter = rvect.begin(); - } + proc_iterator iter = pvect.begin(); + while (iter != pvect.end()) + { + hist.remove(*(*iter)); + iter = pvect.begin(); + } + + const Environment::Resources& rvect = env.get_resources(); + typedef Environment::Resources::const_iterator res_iterator; + + res_iterator riter = rvect.begin(); + while (riter != rvect.end()) + { + hist.remove((*riter).first); + riter = rvect.begin(); + } } void XMLSerializer::read_doc(xmlDocPtr doc, XMLSerializerFactory& fact) throw(SerializerError) { - /* - * Check the document is of the right kind - */ - xmlNodePtr root; - root = xmlDocGetRootElement(doc); - if (root == NULL) { - xmlFreeDoc(doc); - xmlCleanupParser(); - throw SerializerError("Reading Error: xml doc is empty."); - } + /* + * Check the document is of the right kind + */ + xmlNodePtr root; + root = xmlDocGetRootElement(doc); + if (root == NULL) + { + xmlFreeDoc(doc); + xmlCleanupParser(); + throw SerializerError("Reading Error: xml doc is empty."); + } - xmlNodePtr cur; - cur = root->children; - while(cur!=NULL) + xmlNodePtr cur; + cur = root->children; + while (cur != NULL) + { + Glib::ustring name((const char *)cur->name); + if (name == "resources") { - Glib::ustring name((const char *)cur->name); - if(name=="resources") - { - read_resources(cur, fact); - } - if(name=="schedulables") - { - read_schedulables(cur, fact); - } - cur = cur->next; + read_resources(cur, fact); } + if (name == "schedulables") + { + read_schedulables(cur, fact); + } + cur = cur->next; + } } XMLSerializerFactory::Parameters* read_properties(xmlAttrPtr prop) { - if(prop==NULL) + if (prop == NULL) return NULL; - - XMLSerializerFactory::Parameters* par=new XMLSerializerFactory::Parameters(); - while (prop != NULL) { - if(prop->children && xmlNodeIsText(prop->children)){ + + XMLSerializerFactory::Parameters* par = new XMLSerializerFactory::Parameters(); + while (prop != NULL) + { + if (prop->children && xmlNodeIsText(prop->children)) + { xmlChar *key = xmlNodeGetContent (prop->children); // xmlChar *key = xmlNodeListGetString(doc, prop->children, 1); - if(key!=NULL) + if (key != NULL) { std::pair key_value(Glib::ustring((const char *)prop->name), Glib::ustring((const char *)key)); par->insert(key_value); @@ -276,129 +279,129 @@ XMLSerializerFactory::Parameters* read_properties(xmlAttrPtr prop) void XMLSerializer::read_resources(xmlNodePtr resources_node, XMLSerializerFactory& fact) { - xmlNodePtr cur; - cur = resources_node->children; - while(cur!=NULL) + xmlNodePtr cur; + cur = resources_node->children; + while (cur != NULL) + { + Glib::ustring node_name((const char *)cur->name); + if (node_name == "resource") { - Glib::ustring node_name((const char *)cur->name); - if(node_name=="resource") + xmlAttrPtr prop = cur->properties; + XMLSerializerFactory::Parameters* par = read_properties(prop); + if (par != NULL) { - xmlAttrPtr prop = cur->properties; - XMLSerializerFactory::Parameters* par=read_properties(prop); - if(par!=NULL) - { - fact.factory_method(Glib::ustring("Resource"), *par); - } - // fact.create_resource(*par); + fact.factory_method(Glib::ustring("Resource"), *par); } - - cur = cur->next; + // fact.create_resource(*par); } + + cur = cur->next; + } } void XMLSerializer::read_schedulables(xmlNodePtr schedulables_node, XMLSerializerFactory& fact) { - if(schedulables_node==NULL) - return; - - xmlNodePtr cur; - cur = schedulables_node->children; - while(cur!=NULL) - { - Glib::ustring node_name((const char *)cur->name); - if(node_name=="process") - { - xmlAttrPtr prop = cur->properties; - XMLSerializerFactory::Parameters* par=read_properties(prop); - if(par!=NULL) - { - fact.factory_method(Glib::ustring("Process"), *par); - } - // pass the "threads node" - read_threads(cur->children, fact); - } + if (schedulables_node == NULL) + return; - cur = cur->next; + xmlNodePtr cur; + cur = schedulables_node->children; + while (cur != NULL) + { + Glib::ustring node_name((const char *)cur->name); + if (node_name == "process") + { + xmlAttrPtr prop = cur->properties; + XMLSerializerFactory::Parameters* par = read_properties(prop); + if (par != NULL) + { + fact.factory_method(Glib::ustring("Process"), *par); + } + // pass the "threads node" + read_threads(cur->children, fact); } + + cur = cur->next; + } } void XMLSerializer::read_threads(xmlNodePtr threads_node, XMLSerializerFactory& fact) { - if(threads_node==NULL) - return; - - xmlNodePtr cur; - cur = threads_node->children; - while(cur!=NULL) - { - Glib::ustring node_name((const char *)cur->name); - if(node_name=="thread") - { - xmlAttrPtr prop = cur->properties; - XMLSerializerFactory::Parameters* par=read_properties(prop); - if(par!=NULL) - { - fact.factory_method(Glib::ustring("Thread"), *par); - } - // pass the "requests node" - read_requests(cur->children, fact); - } + if (threads_node == NULL) + return; - cur = cur->next; + xmlNodePtr cur; + cur = threads_node->children; + while (cur != NULL) + { + Glib::ustring node_name((const char *)cur->name); + if (node_name == "thread") + { + xmlAttrPtr prop = cur->properties; + XMLSerializerFactory::Parameters* par = read_properties(prop); + if (par != NULL) + { + fact.factory_method(Glib::ustring("Thread"), *par); + } + // pass the "requests node" + read_requests(cur->children, fact); } + + cur = cur->next; + } } void XMLSerializer::read_requests(xmlNodePtr requests_node, XMLSerializerFactory& fact) { - if(requests_node==NULL) - { - return; - } - - xmlNodePtr cur; - cur = requests_node->children; - while(cur!=NULL) - { - Glib::ustring node_name((const char *)cur->name); - if(node_name=="request") - { - xmlAttrPtr prop = cur->properties; - XMLSerializerFactory::Parameters* par=read_properties(prop); - if(par!=NULL) - { - fact.factory_method(Glib::ustring("Request"), *par); - } - // pass the "subrequest nodes" - read_subrequests(cur->children, fact); - } + if (requests_node == NULL) + { + return; + } - cur = cur->next; + xmlNodePtr cur; + cur = requests_node->children; + while (cur != NULL) + { + Glib::ustring node_name((const char *)cur->name); + if (node_name == "request") + { + xmlAttrPtr prop = cur->properties; + XMLSerializerFactory::Parameters* par = read_properties(prop); + if (par != NULL) + { + fact.factory_method(Glib::ustring("Request"), *par); + } + // pass the "subrequest nodes" + read_subrequests(cur->children, fact); } + + cur = cur->next; + } } void XMLSerializer::read_subrequests(xmlNodePtr subrequest_node, XMLSerializerFactory& fact) { - if(subrequest_node==NULL) - { - return; - } - - xmlNodePtr cur; - cur = subrequest_node; - while(cur!=NULL) - { - Glib::ustring node_name((const char *)cur->name); - if(node_name=="subrequest") - { - xmlAttrPtr prop = cur->properties; - XMLSerializerFactory::Parameters* par=read_properties(prop); - if(par!=NULL) - { - fact.factory_method(Glib::ustring("SubRequest"), *par); - } - } + if (subrequest_node == NULL) + { + return; + } - cur = cur->next; + xmlNodePtr cur; + cur = subrequest_node; + while (cur != NULL) + { + Glib::ustring node_name((const char *)cur->name); + if (node_name == "subrequest") + { + xmlAttrPtr prop = cur->properties; + XMLSerializerFactory::Parameters* par = read_properties(prop); + if (par != NULL) + { + fact.factory_method(Glib::ustring("SubRequest"), *par); + } } + + cur = cur->next; + } } /* comment */ diff --git a/plugins/xmlsave/src/xml_serializer.hh b/plugins/xmlsave/src/xml_serializer.hh index de47820..e0ac63e 100644 --- a/plugins/xmlsave/src/xml_serializer.hh +++ b/plugins/xmlsave/src/xml_serializer.hh @@ -92,7 +92,7 @@ namespace sgpem then calls fill_resources and fill_schedulables to fill all with data. */ void fill_doc(xmlDocPtr doc, const History& hist); - + /** \brief Take a resources node and fill it with the data @@ -100,7 +100,7 @@ namespace sgpem Uses an XMLVisitor object to do the task. */ // void fill_resources(xmlNodePtr resources_node, const History& hist); - + /** \brief Take a schedulables node and fill it with the data @@ -125,7 +125,7 @@ namespace sgpem rebuild the correct image using the XMLSerializerFactory object. */ void read_doc(xmlDocPtr doc, XMLSerializerFactory& fact) throw(SerializerError); - + /** \brief Restore all the resources from the passed xml node @@ -134,7 +134,7 @@ namespace sgpem object. */ void read_resources(xmlNodePtr resources_node, XMLSerializerFactory& fact); - + /** \brief Restore all the schedulables (processes) from the passed xml node @@ -143,7 +143,7 @@ namespace sgpem XMLSerializerFactory object. */ void read_schedulables(xmlNodePtr schedulables_node, XMLSerializerFactory& fact); - + /** \brief Restore all threads from the passed xml node @@ -152,7 +152,7 @@ namespace sgpem XMLSerializerFactory object. */ void read_threads(xmlNodePtr schedulables_node, XMLSerializerFactory& fact); - + /** \brief Restore all the requests from the passed xml node @@ -161,7 +161,7 @@ namespace sgpem XMLSerializerFactory object. */ void read_requests(xmlNodePtr schedulables_node, XMLSerializerFactory& fact); - + /** \brief Restore all the subrequests from the passed xml node diff --git a/plugins/xmlsave/src/xml_serializer_factory.cc b/plugins/xmlsave/src/xml_serializer_factory.cc index 1a0ed3a..e9ffa79 100644 --- a/plugins/xmlsave/src/xml_serializer_factory.cc +++ b/plugins/xmlsave/src/xml_serializer_factory.cc @@ -35,13 +35,11 @@ using namespace std; XMLSerializerFactory::XMLSerializerFactory(History& hist) - : _hist(&hist) -{ -} + : _hist(&hist) +{} XMLSerializerFactory::~XMLSerializerFactory() -{ -} +{} History* XMLSerializerFactory::get_history() { @@ -51,27 +49,27 @@ History* XMLSerializerFactory::get_history() void XMLSerializerFactory::factory_method(const Glib::ustring& class_name, Parameters& parameters) throw(SerializerError) { - if(class_name == "Resource") + if (class_name == "Resource") { create_resource(parameters); } - else if(class_name == "Process") + else if (class_name == "Process") { create_process(parameters); } - else if(class_name == "Thread") + else if (class_name == "Thread") { create_thread(parameters); } - else if(class_name == "Request") + else if (class_name == "Request") { create_request(parameters); } - else if(class_name == "SubRequest") + else if (class_name == "SubRequest") { create_subrequest(parameters); } - else + else { throw SerializerError("Factory for Unknown class: " + class_name + " doesn't exists."); } @@ -85,48 +83,53 @@ XMLSerializerFactory::create_resource(Parameters& parameters) Glib::ustring name; Glib::ustring key("0"); - int arrival_time=0; - int how_many=1; - bool preemptable=false; + int arrival_time = 0; + int how_many = 1; + bool preemptable = false; int old_key; Parameters::iterator pos; - + // read "name" property pos = parameters.find(Glib::ustring("name")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { name = pos->second; } // read "key" property pos = parameters.find(Glib::ustring("id")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { Glib::ustring id = key = pos->second; - if(id.length()>6 && id.substr(0,6)==Glib::ustring("reskey")) + if (id.length() > 6 && id.substr(0, 6) == Glib::ustring("reskey")) { key = id.substr(6); string_to_int(key, old_key); } } - + // read "preemptable" property pos = parameters.find(Glib::ustring("preemptable")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { preemptable = (pos->second == "true"); } - + // read "arrival-time" property pos = parameters.find(Glib::ustring("arrival-time")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, arrival_time); } - + // read "how-many" property pos = parameters.find(Glib::ustring("how-many")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, how_many); } - + History::ResourcePair respair = _hist->add_resource(name, preemptable, how_many, arrival_time); _temp_map.insert(TempMap::value_type((resource_key_t)old_key, respair.first)); @@ -142,25 +145,28 @@ XMLSerializerFactory::create_process(Parameters& parameters) { Glib::ustring name; - int arrival_time=0; - int priority=1; + int arrival_time = 0; + int priority = 1; Parameters::iterator pos; - + // read "name" property pos = parameters.find(Glib::ustring("name")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { name = pos->second; } // read "arrival-time" property pos = parameters.find(Glib::ustring("arrival-time")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, arrival_time); } - + // read "priority" property pos = parameters.find(Glib::ustring("priority")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, priority); } @@ -178,32 +184,36 @@ XMLSerializerFactory::create_thread(Parameters& parameters) { Glib::ustring name; - int arrival_time=0; - int lasts_for=0; - int priority=1; + int arrival_time = 0; + int lasts_for = 0; + int priority = 1; Parameters::iterator pos; - + // read "name" property pos = parameters.find(Glib::ustring("name")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { name = pos->second; } // read "arrival-time" property pos = parameters.find(Glib::ustring("arrival-delta")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, arrival_time); } - + // read "priority" property pos = parameters.find(Glib::ustring("priority")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, priority); } // read "priority" property pos = parameters.find(Glib::ustring("lasts-for")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, lasts_for); } @@ -218,12 +228,13 @@ XMLSerializerFactory::create_request(Parameters& parameters) // if(_hist!=NULL) { - int arrival_time=0; + int arrival_time = 0; Parameters::iterator pos; // read "arrival-time" property pos = parameters.find(Glib::ustring("arrival-time")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, arrival_time); } @@ -238,26 +249,28 @@ XMLSerializerFactory::create_subrequest(Parameters& parameters) // if(_hist!=NULL) { - int old_key=0; - int lasts_for=0; + int old_key = 0; + int lasts_for = 0; //int places=1; Parameters::iterator pos; resource_key_t new_key = 0; - - + + // read "arrival-time" property pos = parameters.find(Glib::ustring("resource")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, old_key); - + TempMap::iterator temp_pos; temp_pos = _temp_map.find((resource_key_t)old_key); - if (temp_pos != _temp_map.end()) { + if (temp_pos != _temp_map.end()) + { //take key of resource in _hist new_key = temp_pos->second; } } - + // read "priority" property //pos = parameters.find(Glib::ustring("how-many")); //if (pos != parameters.end()) { @@ -266,7 +279,8 @@ XMLSerializerFactory::create_subrequest(Parameters& parameters) // read "priority" property pos = parameters.find(Glib::ustring("lasts-for")); - if (pos != parameters.end()) { + if (pos != parameters.end()) + { string_to_int(pos->second, lasts_for); } diff --git a/plugins/xmlsave/src/xml_serializer_factory.hh b/plugins/xmlsave/src/xml_serializer_factory.hh index b0fa3a0..63bf348 100644 --- a/plugins/xmlsave/src/xml_serializer_factory.hh +++ b/plugins/xmlsave/src/xml_serializer_factory.hh @@ -51,12 +51,12 @@ namespace sgpem { public: typedef std::map Parameters; - + /** \brief Contructor takes an history as readed data destination */ XMLSerializerFactory(History& hist); - + /** \brief A destructor, nothing else */ @@ -83,22 +83,22 @@ namespace sgpem typedef Environment::resource_key_t resource_key_t; // associate old keys with new ones typedef std::map TempMap; - + /** Resource factory from given parameters */ History::ResourcePair create_resource(Parameters& parameters); - + /** Process factory from given parameters */ Process& create_process(Parameters& parameters); - + /** Thread factory from given parameters */ Thread& create_thread(Parameters& parameters); - + /** Request factory from given parameters */ diff --git a/plugins/xmlsave/src/xml_visitor.cc b/plugins/xmlsave/src/xml_visitor.cc index eb55add..baa55e7 100644 --- a/plugins/xmlsave/src/xml_visitor.cc +++ b/plugins/xmlsave/src/xml_visitor.cc @@ -36,19 +36,17 @@ using namespace sgpem; XMLVisitor::XMLVisitor(xmlNodePtr current) - : _current(current) -{ -} + : _current(current) +{} XMLVisitor::~XMLVisitor() -{ -} +{} void XMLVisitor::from_resource(const Resource& obj) throw(SerializerError) { throw SerializerError( _("XMLVisitor: unsupported method from_resource(const Resource& obj)") - ); + ); } @@ -100,9 +98,9 @@ void XMLVisitor::from_resource(const Resource& obj, const Glib::ustring& key) th void XMLVisitor::from_history(xmlNodePtr parent, const History& hist) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { - from_environment(parent, hist.get_last_environment()); + from_environment(parent, hist.get_last_environment()); } else { @@ -113,7 +111,7 @@ void XMLVisitor::from_history(xmlNodePtr parent, const History& hist) throw(Seri void XMLVisitor::from_environment(xmlNodePtr parent, const Environment& env) throw(SerializerError) { - if(parent==NULL) + if (parent == NULL) { throw SerializerError(_("Error trying to add data to empty XML node.")); } @@ -124,10 +122,10 @@ void XMLVisitor::from_environment(xmlNodePtr parent, const Environment& env) thr xmlNodePtr resources_node = xmlNewChild(parent, NULL, (const xmlChar *) "resources", NULL); const Environment::Resources& rvect = env.get_resources(); typedef Environment::Resources::const_iterator res_iterator; - + res_iterator iter = rvect.begin(); res_iterator end = rvect.end(); - while(iter!=end) + while (iter != end) { //XMLVisitor xvisit(resources_node); Glib::ustring key; @@ -144,10 +142,10 @@ void XMLVisitor::from_environment(xmlNodePtr parent, const Environment& env) thr xmlNodePtr schedulables_node = xmlNewChild(parent, NULL, (const xmlChar *) "schedulables", NULL); const Environment::Processes& pvect = env.get_processes(); typedef std::vector::const_iterator proc_iterator; - + proc_iterator iter = pvect.begin(); proc_iterator end = pvect.end(); - while(iter!=end) + while (iter != end) { // XMLVisitor xvisit(schedulables_node); // xvisit.from_process(*(*iter)); @@ -160,7 +158,7 @@ void XMLVisitor::from_environment(xmlNodePtr parent, const Environment& env) thr void XMLVisitor::from_resource(xmlNodePtr parent, const Resource& obj, const Glib::ustring& key) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { Glib::ustring id = "reskey" + key; Glib::ustring strPreemptible("false"); // fixed?? @@ -184,7 +182,7 @@ void XMLVisitor::from_resource(xmlNodePtr parent, const Resource& obj, const Gli void XMLVisitor::from_process(xmlNodePtr parent, const Process& obj) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { Glib::ustring strPriority; Glib::ustring strArrivalTime; @@ -205,10 +203,10 @@ void XMLVisitor::from_process(xmlNodePtr parent, const Process& obj) throw(Seria const Threads& tvect = ((Process&)obj).get_threads(); thr_iterator iter = tvect.begin(); thr_iterator end = tvect.end(); - while(iter!=end) + while (iter != end) { const Thread* t = *iter; - + from_thread(threads_node, *(*iter)); iter++; } @@ -222,7 +220,7 @@ void XMLVisitor::from_process(xmlNodePtr parent, const Process& obj) throw(Seria void XMLVisitor::from_thread(xmlNodePtr parent, const Thread& obj) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { Glib::ustring strPriority; @@ -237,7 +235,7 @@ void XMLVisitor::from_thread(xmlNodePtr parent, const Thread& obj) throw(Seriali xmlNewProp(thread_node, (const xmlChar *) "priority", (const xmlChar *) strPriority.c_str()); xmlNewProp(thread_node, (const xmlChar *) "arrival-delta", (const xmlChar *) strArrivalTime.c_str()); xmlNewProp(thread_node, (const xmlChar *) "lasts-for", (const xmlChar *) strLastsTime.c_str()); - + // make a requests subnode xmlNodePtr requests_node = xmlNewChild(thread_node, NULL, (const xmlChar *) "requests", NULL); // iterate on requests @@ -246,10 +244,10 @@ void XMLVisitor::from_thread(xmlNodePtr parent, const Thread& obj) throw(Seriali const Requests& rvect = ((Thread&)obj).get_requests(); req_iterator iter = rvect.begin(); req_iterator end = rvect.end(); - while(iter!=end) + while (iter != end) { const Request* r = *iter; - + from_request(requests_node, *(*iter)); iter++; } @@ -263,7 +261,7 @@ void XMLVisitor::from_thread(xmlNodePtr parent, const Thread& obj) throw(Seriali void XMLVisitor::from_request(xmlNodePtr parent, const Request& obj) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { Glib::ustring strArrivalTime; @@ -271,7 +269,7 @@ void XMLVisitor::from_request(xmlNodePtr parent, const Request& obj) throw(Seria xmlNodePtr request_node = xmlNewChild(parent, NULL, (const xmlChar *) "request", NULL); xmlNewProp(request_node, (const xmlChar *) "arrival-time", (const xmlChar *) strArrivalTime.c_str()); - + // make a requests subnode // xmlNodePtr subrequests_node = xmlNewChild(thread_node, NULL, (const xmlChar *) "requests", NULL); // iterate on subrequests @@ -280,7 +278,7 @@ void XMLVisitor::from_request(xmlNodePtr parent, const Request& obj) throw(Seria const SubRequests& srvect = ((Request&)obj).get_subrequests(); subreq_iterator iter = srvect.begin(); subreq_iterator end = srvect.end(); - while(iter!=end) + while (iter != end) { const SubRequest* sr = *iter; from_subrequest(request_node, *(*iter)); @@ -296,7 +294,7 @@ void XMLVisitor::from_request(xmlNodePtr parent, const Request& obj) throw(Seria void XMLVisitor::from_subrequest(xmlNodePtr parent, const SubRequest& obj) throw(SerializerError) { - if(parent!=NULL) + if (parent != NULL) { Glib::ustring strResource; diff --git a/plugins/xmlsave/src/xml_visitor.hh b/plugins/xmlsave/src/xml_visitor.hh index 8b3f8fb..1f4d1bc 100644 --- a/plugins/xmlsave/src/xml_visitor.hh +++ b/plugins/xmlsave/src/xml_visitor.hh @@ -83,39 +83,39 @@ namespace sgpem Throw an exception. */ virtual void from_resource(const Resource& obj) throw(SerializerError); - + /** \brief Add output to the serializer taking data from resource and key BUG FIXED: This save a resource with her own associated key. Wrapper method: call from_resource(xmlNodePtr parent, const Resource& obj, const Glib::ustring& key); */ virtual void from_resource(const Resource& obj, const Glib::ustring& key) throw(SerializerError); - + /** \brief Add output to the serializer taking data from process Wrapper method: call from_process(xmlNodePtr parent, const Process& obj); */ virtual void from_process(const Process& obj) throw(SerializerError); - + /** \brief Add output to the serializer taking data from thread Wrapper method: call from_thread(xmlNodePtr parent, const Thread& obj); */ virtual void from_thread(const Thread& obj) throw(SerializerError); - + /** \brief Add output to the serializer taking data from request Wrapper method: call from_request(xmlNodePtr parent, const Request& obj); */ virtual void from_request(const Request& obj) throw(SerializerError); - + /** \brief Add output to the serializer taking data from subrequest Wrapper method: call from_subrequest(xmlNodePtr parent, const SubRequest& obj); */ virtual void from_subrequest(const SubRequest& obj) throw(SerializerError); - - + + private: void from_history(xmlNodePtr parent, const History& obj) throw(SerializerError); void from_environment(xmlNodePtr parent, const Environment& obj) throw(SerializerError); diff --git a/src/backend/concrete_environment.cc b/src/backend/concrete_environment.cc index dc499df..ee0a324 100644 --- a/src/backend/concrete_environment.cc +++ b/src/backend/concrete_environment.cc @@ -42,82 +42,82 @@ ConcreteEnvironment::ConcreteEnvironment() ConcreteEnvironment::ConcreteEnvironment(const ConcreteEnvironment& ce) : - Environment(ce), _resources(ce._resources), _processes(), _sched_queue(), _sreq_queues(ce._sreq_queues) + Environment(ce), _resources(ce._resources), _processes(), _sched_queue(), _sreq_queues(ce._sreq_queues) { - // The ReadyQueue won't be copied. Pointers to objects contained into - // the ready queue _will_ have changed in the new one. The ready queue - // needs to be reset: it is Scheduler that builds it again from time to time. + // The ReadyQueue won't be copied. Pointers to objects contained into + // the ready queue _will_ have changed in the new one. The ready queue + // needs to be reset: it is Scheduler that builds it again from time to time. - // Update resource pointers in a way you won't like :-) - { - for(Resources::iterator it = _resources.begin(); it != _resources.end(); it++) - it->second = new DynamicResource(dynamic_cast(*it->second)); - } + // Update resource pointers in a way you won't like :-) + { + for (Resources::iterator it = _resources.begin(); it != _resources.end(); it++) + it->second = new DynamicResource(dynamic_cast(*it->second)); + } // DynamicProcess object need to be copied. // The deep copy is guaranteed by the DynamicProcess copy constructor - { - const Processes& ce_proc = ce._processes; - insert_iterator dest(_processes, _processes.begin()); - for(Processes::const_iterator orig = ce_proc.begin(); orig != ce_proc.end(); orig++) - *dest++ = new DynamicProcess(dynamic_cast(**orig)); - } + { + const Processes& ce_proc = ce._processes; + insert_iterator dest(_processes, _processes.begin()); + for (Processes::const_iterator orig = ce_proc.begin(); orig != ce_proc.end(); orig++) + *dest++ = new DynamicProcess(dynamic_cast(**orig)); + } - // Update the subrequest queues. + // Update the subrequest queues. - // for each subrequest - typedef Processes::const_iterator it1_t; + // for each subrequest + typedef Processes::const_iterator it1_t; - typedef std::vector v2_t; - typedef v2_t::const_iterator it2_t; + typedef std::vector v2_t; + typedef v2_t::const_iterator it2_t; - typedef std::vector v3_t; - typedef v3_t::const_iterator it3_t; + typedef std::vector v3_t; + typedef v3_t::const_iterator it3_t; - typedef std::vector v4_t; - typedef v4_t::const_iterator it4_t; + typedef std::vector v4_t; + typedef v4_t::const_iterator it4_t; - typedef SubRequestQueue::iterator it5_t; + typedef SubRequestQueue::iterator it5_t; + + for (it1_t it1 = _processes.begin(); it1 != _processes.end(); it1++) + { + const v2_t& threads = (*it1)->get_threads(); + for (it2_t it2 = threads.begin(); it2 != threads.end(); it2++) + { + const v3_t& reqs = (*it2)->get_requests(); + for (it3_t it3 = reqs.begin(); it3 != reqs.end(); it3++) + { + // an optimization here: there is no reason in iterating through + // future or exausted requests. (Do you know why?) + const v4_t& subr = (*it3)->get_subrequests(); + for (it4_t it4 = subr.begin(); it4 != subr.end(); it4++) + { + SubRequest::state curr_state = (*it4)->get_state(); + if (curr_state != Request::state_future && curr_state != Request::state_exhausted) + { + // the subrequest is the following queue: + SubRequestQueue & queue = get_request_queue((*it4)->get_resource_key()); + // we must replace the old pointer: + bool found = false; + for (it5_t it5 = queue.begin(); !found && it5 != queue.end(); it5++) + { + DynamicSubRequest& _old = dynamic_cast(**it5); + DynamicSubRequest& _new = dynamic_cast(**it4); + if (&_old.get_core() == &_new.get_core()) + { + found = true; + *it5 = *it4; + } + } + } + } + } + } + } - for(it1_t it1 = _processes.begin(); it1 != _processes.end(); it1++) - { - const v2_t& threads = (*it1)->get_threads(); - for(it2_t it2 = threads.begin(); it2 != threads.end(); it2++) - { - const v3_t& reqs = (*it2)->get_requests(); - for(it3_t it3 = reqs.begin(); it3 != reqs.end(); it3++) - { - // an optimization here: there is no reason in iterating through - // future or exausted requests. (Do you know why?) - const v4_t& subr = (*it3)->get_subrequests(); - for(it4_t it4 = subr.begin(); it4 != subr.end(); it4++) - { - SubRequest::state curr_state = (*it4)->get_state(); - if(curr_state != Request::state_future && curr_state != Request::state_exhausted) - { - // the subrequest is the following queue: - SubRequestQueue & queue = get_request_queue((*it4)->get_resource_key()); - // we must replace the old pointer: - bool found = false; - for(it5_t it5 = queue.begin(); !found && it5 != queue.end(); it5++) - { - DynamicSubRequest& _old = dynamic_cast(**it5); - DynamicSubRequest& _new = dynamic_cast(**it4); - if (&_old.get_core() == &_new.get_core()) - { - found = true; - *it5 = *it4; - } - } - } - } - } - } - } - } @@ -195,14 +195,14 @@ ConcreteEnvironment::get_sorted_queue() ConcreteEnvironment::~ConcreteEnvironment() { - // This call will invoke the DynamicProcess virtual destructor - // Which will delete on cascade all DynamicThreads and so on. - for_each(_processes.begin(), _processes.end(), - memory::deletor()); + // This call will invoke the DynamicProcess virtual destructor + // Which will delete on cascade all DynamicThreads and so on. + for_each(_processes.begin(), _processes.end(), + memory::deletor()); - // We do the same with Resources. - for(Resources::iterator it = _resources.begin(); it != _resources.end(); it++) - delete it->second; + // We do the same with Resources. + for (Resources::iterator it = _resources.begin(); it != _resources.end(); it++) + delete it->second; // After this, the destructor of _sched_queue is invoked (only invalid pointers) // After that, the destructor of _processes is invoked (only invalid pointers) diff --git a/src/backend/concrete_environment.hh b/src/backend/concrete_environment.hh index 7cf2d3c..6740b64 100644 --- a/src/backend/concrete_environment.hh +++ b/src/backend/concrete_environment.hh @@ -62,12 +62,12 @@ namespace sgpem /// considered instant. /// /// The Process objects returned are actually DynamicProcess - /// objects. A downcast to DynamicProcess is guaranteed to be + /// objects. A downcast to DynamicProcess is guaranteed to be /// always safe. /// /// \return a constant set of snapshots of processes virtual const Processes& - get_processes() const; + get_processes() const; @@ -76,7 +76,7 @@ namespace sgpem /// \return a set of snapshots of processes /// \see get_processes() virtual Processes& - get_processes(); + get_processes(); @@ -93,13 +93,13 @@ namespace sgpem /// class which returns the Resource object indexed. /// /// The Resource objects returned are actually DynamicResource - /// objects. A downcast to DynamicResource is guaranteed to be + /// objects. A downcast to DynamicResource is guaranteed to be /// always safe. /// /// \return a indexed constant set of snapshot of resources. /// \see DynamicSybrequest::get_resource() virtual const Resources& - get_resources() const; + get_resources() const; @@ -108,7 +108,7 @@ namespace sgpem /// \return an indexed set of snapshots of resources /// \see get_resources() virtual Resources& - get_resources(); + get_resources(); @@ -118,16 +118,16 @@ namespace sgpem /// are waiting for getting control of a limited-access resource. /// /// The Request objects returned are actually DynamicRequest - /// objects. A downcast to DynamicRequest is guaranteed to be + /// objects. A downcast to DynamicRequest is guaranteed to be /// always safe. /// /// \param resource The resource the requests are for /// \return The current ready requests queue. virtual const SubRequestQueue& - get_request_queue(resource_key_t resource_key) const; + get_request_queue(resource_key_t resource_key) const; SubRequestQueue& - get_request_queue(resource_key_t resource_key); + get_request_queue(resource_key_t resource_key); @@ -150,7 +150,7 @@ namespace sgpem /// /// \return the current ready queue (constant). virtual const ReadyQueue& - get_sorted_queue() const; + get_sorted_queue() const; @@ -159,14 +159,14 @@ namespace sgpem /// \return the current ready queue. /// \see get_sorted_queue() virtual ReadyQueue& - get_sorted_queue(); - + get_sorted_queue(); + /// \brief The standard virtual destructor. /// The standard virtual destructor. virtual - ~ConcreteEnvironment(); + ~ConcreteEnvironment(); private: @@ -175,11 +175,11 @@ namespace sgpem /// Actually contains only DynamicResource objects. // resources come before processes because of // destruction order. See destructor implementation - Resources _resources; + Resources _resources; /// \brief The container of all Process objecs. /// Actually contains only DynamicProcess objects. - Processes _processes; + Processes _processes; /// \brief The queue of the ready schedulables /// Does not contain the running process. @@ -187,7 +187,8 @@ namespace sgpem SubRequestQueues _sreq_queues; - }; //~ class ConcreteEnvironment + } + ; //~ class ConcreteEnvironment } //~ namespace sgpem diff --git a/src/backend/concrete_history.cc b/src/backend/concrete_history.cc index 7161e47..90f52cd 100644 --- a/src/backend/concrete_history.cc +++ b/src/backend/concrete_history.cc @@ -54,372 +54,372 @@ using memory::deletor; template static bool deep_remove(std::vector& v, const T& obj) { - typedef typename std::vector Vector; - for(typename Vector::iterator it = v.begin(); it != v.end(); it++) - if(**it == obj) - { - delete *it; - v.erase(it); - return true; - } - return false; + typedef typename std::vector Vector; + for (typename Vector::iterator it = v.begin(); it != v.end(); it++) + if (**it == obj) + { + delete *it; + v.erase(it); + return true; + } + return false; } template static T* deep_find(const std::vector& v, const T& obj) { - typedef typename std::vector Vector; - for(typename Vector::const_iterator it = v.begin(); it != v.end(); it++) - if(**it == obj) - { - return *it; - } - return NULL; + typedef typename std::vector Vector; + for (typename Vector::const_iterator it = v.begin(); it != v.end(); it++) + if (**it == obj) + { + return *it; + } + return NULL; } // ----------------- ConcreteHistory::ConcreteHistory() - : History(), _snapshots() + : History(), _snapshots() { - _snapshots.push_back(new ConcreteEnvironment()); + _snapshots.push_back(new ConcreteEnvironment()); } ConcreteHistory::~ConcreteHistory() { - for_each(_snapshots.begin(), _snapshots.end(), - deletor()); + for_each(_snapshots.begin(), _snapshots.end(), + deletor()); } ConcreteHistory::ConcreteHistory(const ConcreteHistory& h) : - History(h) + History(h) { typedef Snapshots::const_iterator SnapIt; - for(SnapIt it = h._snapshots.begin(); it != h._snapshots.end(); ++it) + for (SnapIt it = h._snapshots.begin(); it != h._snapshots.end(); ++it) _snapshots.push_back(new ConcreteEnvironment(*(*it))); } void ConcreteHistory::append_new_environment(ConcreteEnvironment* environment) { - _snapshots.push_back(environment); - notify_change(); + _snapshots.push_back(environment); + notify_change(); } ConcreteHistory::size_t ConcreteHistory::get_size() const { - return _snapshots.size(); + return _snapshots.size(); } -const ConcreteEnvironment& +const ConcreteEnvironment& ConcreteHistory::get_last_environment() const { - // Should always be true: - assert(_snapshots.size() > 0); - return *_snapshots.back(); + // Should always be true: + assert(_snapshots.size() > 0); + return *_snapshots.back(); } -const ConcreteEnvironment& -ConcreteHistory::get_environment_at(position index) const - throw(std::out_of_range) +const ConcreteEnvironment& +ConcreteHistory::get_environment_at(position index) const +throw(std::out_of_range) { - return *_snapshots.at(index); + return *_snapshots.at(index); } -void +void ConcreteHistory::remove(resource_key_t resource_key) { - // Pay attention that initial isn't deleted by reset() - ConcreteEnvironment& initial = *_snapshots.front(); - ConcreteEnvironment::Resources& resources = initial.get_resources(); - ConcreteEnvironment::Resources::iterator found = resources.find(resource_key); - if(found == resources.end()) - return; + // Pay attention that initial isn't deleted by reset() + ConcreteEnvironment& initial = *_snapshots.front(); + ConcreteEnvironment::Resources& resources = initial.get_resources(); + ConcreteEnvironment::Resources::iterator found = resources.find(resource_key); + if (found == resources.end()) + return; - reset(false); + reset(false); - delete found->second; - resources.erase(found); + delete found->second; + resources.erase(found); - // Delete the queue associated with the resource. - ConcreteEnvironment::SubRequestQueues& srq = initial.get_subrequest_queues(); - ConcreteEnvironment::SubRequestQueues::iterator qfound = srq.find(resource_key); - // There is always one! - assert(qfound != srq.end()); - srq.erase(qfound); + // Delete the queue associated with the resource. + ConcreteEnvironment::SubRequestQueues& srq = initial.get_subrequest_queues(); + ConcreteEnvironment::SubRequestQueues::iterator qfound = srq.find(resource_key); + // There is always one! + assert(qfound != srq.end()); + srq.erase(qfound); - // Now search and erase subrequest that had a ref to the - // removed resource + // Now search and erase subrequest that had a ref to the + // removed resource - typedef std::vector Threads; - typedef std::vector Requests; - typedef std::vector SubRequests; + typedef std::vector Threads; + typedef std::vector Requests; + typedef std::vector SubRequests; - // Listening to "The Thing That Should Not Be"... - // all hail the cyclomatic complexity! - ConcreteEnvironment::Processes& processes = initial.get_processes(); - typedef ConcreteEnvironment::Processes::iterator ProcIt; - for(ProcIt it1 = processes.begin(); it1 != processes.end(); it1++) - { - Threads& threads = dynamic_cast(**it1).get_dynamic_threads(); - for(Threads::iterator it2 = threads.begin(); it2 != threads.end(); it2++) - { - Requests& reqs = (*it2)->get_dynamic_requests(); - for(Requests::iterator it3 = reqs.begin(); it3 != reqs.end(); it3++) - { - SubRequests& subr = (*it3)->get_dynamic_subrequests(); - SubRequests::iterator it4 = subr.begin(); - while(it4 != subr.end()) - if((*it4)->get_resource_key() == resource_key) - { - delete *it4; - it4 = subr.erase(it4); - } - else - it4++; - } - } - } //~ end monstrous construct, "The Thing That Should Not Be" - // Chtulhu ftaghn. There are worse things in life. Mother-in-laws, - // for example. Or hangovers. Or being read poetry by a Vogon. - // Although the above construct really rates between the first tens. + // Listening to "The Thing That Should Not Be"... + // all hail the cyclomatic complexity! + ConcreteEnvironment::Processes& processes = initial.get_processes(); + typedef ConcreteEnvironment::Processes::iterator ProcIt; + for (ProcIt it1 = processes.begin(); it1 != processes.end(); it1++) + { + Threads& threads = dynamic_cast(**it1).get_dynamic_threads(); + for (Threads::iterator it2 = threads.begin(); it2 != threads.end(); it2++) + { + Requests& reqs = (*it2)->get_dynamic_requests(); + for (Requests::iterator it3 = reqs.begin(); it3 != reqs.end(); it3++) + { + SubRequests& subr = (*it3)->get_dynamic_subrequests(); + SubRequests::iterator it4 = subr.begin(); + while (it4 != subr.end()) + if ((*it4)->get_resource_key() == resource_key) + { + delete *it4; + it4 = subr.erase(it4); + } + else + it4++; + } + } + } //~ end monstrous construct, "The Thing That Should Not Be" + // Chtulhu ftaghn. There are worse things in life. Mother-in-laws, + // for example. Or hangovers. Or being read poetry by a Vogon. + // Although the above construct really rates between the first tens. - notify_change(); + notify_change(); } void ConcreteHistory::remove(Process& process) { - // Pay attention that initial isn't deleted by reset() - ConcreteEnvironment& initial = *_snapshots.front(); - ConcreteEnvironment::Processes& processes = initial.get_processes(); - bool found = deep_remove(processes, process); - if(found) - reset(true); + // Pay attention that initial isn't deleted by reset() + ConcreteEnvironment& initial = *_snapshots.front(); + ConcreteEnvironment::Processes& processes = initial.get_processes(); + bool found = deep_remove(processes, process); + if (found) + reset(true); } -void +void ConcreteHistory::remove(Thread& thread) { - DynamicThread& dyn_thr = dynamic_cast(thread); + DynamicThread& dyn_thr = dynamic_cast(thread); - // Pay attention that initial isn't deleted by reset() - ConcreteEnvironment& initial = *_snapshots.front(); - ConcreteEnvironment::Processes& processes = initial.get_processes(); + // Pay attention that initial isn't deleted by reset() + ConcreteEnvironment& initial = *_snapshots.front(); + ConcreteEnvironment::Processes& processes = initial.get_processes(); Process* found = deep_find(processes, dyn_thr.get_process()); - if(found == NULL) - return; // not found, just return. - - DynamicProcess& dynamic_found = dynamic_cast(*found); - bool removed = deep_remove(dynamic_found.get_dynamic_threads(), dyn_thr); + if (found == NULL) + return; // not found, just return. - if(removed) - reset(true); + DynamicProcess& dynamic_found = dynamic_cast(*found); + bool removed = deep_remove(dynamic_found.get_dynamic_threads(), dyn_thr); + + if (removed) + reset(true); } - + void ConcreteHistory::remove(Request& request) { - DynamicRequest& dyn_req = dynamic_cast(request); - DynamicThread& dyn_thr = dyn_req.get_thread(); - DynamicProcess& dyn_proc = dyn_thr.get_process(); + DynamicRequest& dyn_req = dynamic_cast(request); + DynamicThread& dyn_thr = dyn_req.get_thread(); + DynamicProcess& dyn_proc = dyn_thr.get_process(); - // Pay attention that initial isn't deleted by reset() - ConcreteEnvironment& initial = *_snapshots.front(); - ConcreteEnvironment::Processes& processes = initial.get_processes(); - - Process* proc_ref = deep_find(processes, dyn_proc); - DynamicProcess* dyn_proc_ref = dynamic_cast(proc_ref); - if(dyn_proc_ref == NULL) - return; // not found, just return. - DynamicThread* thr_ref = deep_find(dyn_proc_ref->get_dynamic_threads(), dyn_thr); - if(thr_ref == NULL) - return; // not found, just return. - - bool removed = deep_remove(thr_ref->get_dynamic_requests(), dyn_req); - - if(removed) - reset(true); -} - - -void -ConcreteHistory::remove(SubRequest& subrequest) -{ - // this function makes one relevant assumption: - // the initial environment does contain empty request queues only. - - DynamicSubRequest& dyn_sub = dynamic_cast(subrequest); - DynamicRequest& dyn_req = dyn_sub.get_request(); - DynamicThread& dyn_thr = dyn_req.get_thread(); - DynamicProcess& dyn_proc = dyn_thr.get_process(); - - // Pay attention that initial isn't deleted by reset() - ConcreteEnvironment& initial = *_snapshots.front(); - ConcreteEnvironment::Processes& processes = initial.get_processes(); + // Pay attention that initial isn't deleted by reset() + ConcreteEnvironment& initial = *_snapshots.front(); + ConcreteEnvironment::Processes& processes = initial.get_processes(); Process* proc_ref = deep_find(processes, dyn_proc); - DynamicProcess* dyn_proc_ref = dynamic_cast(proc_ref); - if(dyn_proc_ref == NULL) - return; // not found, just return. - DynamicThread* thr_ref = deep_find(dyn_proc_ref->get_dynamic_threads(), dyn_thr); - if(thr_ref == NULL) - return; // not found, just return. - DynamicRequest* req_ref = deep_find(thr_ref->get_dynamic_requests(), dyn_req); - if(req_ref == NULL) - return; // not found, just return. + DynamicProcess* dyn_proc_ref = dynamic_cast(proc_ref); + if (dyn_proc_ref == NULL) + return; // not found, just return. + DynamicThread* thr_ref = deep_find(dyn_proc_ref->get_dynamic_threads(), dyn_thr); + if (thr_ref == NULL) + return; // not found, just return. - bool removed = deep_remove(req_ref->get_dynamic_subrequests(), dyn_sub); + bool removed = deep_remove(thr_ref->get_dynamic_requests(), dyn_req); - if(removed) - reset(true); + if (removed) + reset(true); } -ConcreteHistory::ResourcePair +void +ConcreteHistory::remove(SubRequest& subrequest) +{ + // this function makes one relevant assumption: + // the initial environment does contain empty request queues only. + + DynamicSubRequest& dyn_sub = dynamic_cast(subrequest); + DynamicRequest& dyn_req = dyn_sub.get_request(); + DynamicThread& dyn_thr = dyn_req.get_thread(); + DynamicProcess& dyn_proc = dyn_thr.get_process(); + + // Pay attention that initial isn't deleted by reset() + ConcreteEnvironment& initial = *_snapshots.front(); + ConcreteEnvironment::Processes& processes = initial.get_processes(); + + Process* proc_ref = deep_find(processes, dyn_proc); + DynamicProcess* dyn_proc_ref = dynamic_cast(proc_ref); + if (dyn_proc_ref == NULL) + return; // not found, just return. + DynamicThread* thr_ref = deep_find(dyn_proc_ref->get_dynamic_threads(), dyn_thr); + if (thr_ref == NULL) + return; // not found, just return. + DynamicRequest* req_ref = deep_find(thr_ref->get_dynamic_requests(), dyn_req); + if (req_ref == NULL) + return; // not found, just return. + + bool removed = deep_remove(req_ref->get_dynamic_subrequests(), dyn_sub); + + if (removed) + reset(true); +} + + +ConcreteHistory::ResourcePair ConcreteHistory::add_resource(const Glib::ustring& name, - bool preemptable, - size_t places, - size_t availability) + bool preemptable, + size_t places, + size_t availability) { - reset(false); + reset(false); - typedef ConcreteEnvironment::Resources Resources; - typedef ConcreteEnvironment::SubRequestQueue SubRequestQueue; - // And preemptable and availability?? FIXME! + typedef ConcreteEnvironment::Resources Resources; + typedef ConcreteEnvironment::SubRequestQueue SubRequestQueue; + // And preemptable and availability?? FIXME! - StaticResource* core = new StaticResource(name, places); - DynamicResource* resource = new DynamicResource(core); + StaticResource* core = new StaticResource(name, places); + DynamicResource* resource = new DynamicResource(core); - ConcreteEnvironment::Resources& resources = _snapshots.front()->get_resources(); - - // alakazam! Black magic at work... get a unique index for this resource - resource_key_t index = 0; - while(resources.find(index) != resources.end()) - index++; - - // Found a hole in the map, fill it like little Hans, - // its finger and the spilling dam. - Resources::iterator temp = resources.insert(pair(index, resource)).first; - // The same for request queues. - SubRequestQueue emptysrq; - _snapshots.front()->get_subrequest_queues().insert(pair(index, emptysrq)); + ConcreteEnvironment::Resources& resources = _snapshots.front()->get_resources(); - - notify_change(); + // alakazam! Black magic at work... get a unique index for this resource + resource_key_t index = 0; + while (resources.find(index) != resources.end()) + index++; - return *temp; + // Found a hole in the map, fill it like little Hans, + // its finger and the spilling dam. + Resources::iterator temp = resources.insert(pair(index, resource)).first; + // The same for request queues. + SubRequestQueue emptysrq; + _snapshots.front()->get_subrequest_queues().insert(pair(index, emptysrq)); + + + notify_change(); + + return *temp; } -DynamicProcess& +DynamicProcess& ConcreteHistory::add_process(const Glib::ustring& name, - time_t arrival_time, - prio_t base_priority) + time_t arrival_time, + prio_t base_priority) { - reset(false); - - StaticProcess* core = new StaticProcess(name, arrival_time, base_priority); - DynamicProcess* proc = new DynamicProcess(core); + reset(false); - ConcreteEnvironment::Processes& processes = _snapshots.front()->get_processes(); - processes.push_back(proc); + StaticProcess* core = new StaticProcess(name, arrival_time, base_priority); + DynamicProcess* proc = new DynamicProcess(core); - notify_change(); - return *proc; + ConcreteEnvironment::Processes& processes = _snapshots.front()->get_processes(); + processes.push_back(proc); + + notify_change(); + return *proc; } -DynamicThread& +DynamicThread& ConcreteHistory::add_thread(const Glib::ustring& name, - Process& parent, - time_t cpu_time, - time_t arrival_time, - prio_t base_priority) + Process& parent, + time_t cpu_time, + time_t arrival_time, + prio_t base_priority) { - reset(false); - - // Holy cow! *THIS* is ugly!!!! - DynamicProcess& parent_process = dynamic_cast(parent); - StaticProcess& parent_core = parent_process.get_core(); - StaticThread* core = new StaticThread(name, parent_core, cpu_time, arrival_time, base_priority); - DynamicThread* thread = new DynamicThread(core, &parent_process); - - notify_change(); - return *thread; + reset(false); + + // Holy cow! *THIS* is ugly!!!! + DynamicProcess& parent_process = dynamic_cast(parent); + StaticProcess& parent_core = parent_process.get_core(); + StaticThread* core = new StaticThread(name, parent_core, cpu_time, arrival_time, base_priority); + DynamicThread* thread = new DynamicThread(core, &parent_process); + + notify_change(); + return *thread; } -DynamicRequest& +DynamicRequest& ConcreteHistory::add_request(Thread& owner, - time_t instant) + time_t instant) { - reset(false); - - DynamicThread& dyn_owner = dynamic_cast(owner); - StaticThread& owner_core = dyn_owner.get_core(); - - StaticRequest* core = new StaticRequest(&owner_core, instant); - DynamicRequest* req = new DynamicRequest(core, &dyn_owner); + reset(false); - dyn_owner.get_requests().push_back(req); + DynamicThread& dyn_owner = dynamic_cast(owner); + StaticThread& owner_core = dyn_owner.get_core(); - notify_change(); - return *req; + StaticRequest* core = new StaticRequest(&owner_core, instant); + DynamicRequest* req = new DynamicRequest(core, &dyn_owner); + + dyn_owner.get_requests().push_back(req); + + notify_change(); + return *req; } -DynamicSubRequest& +DynamicSubRequest& ConcreteHistory::add_subrequest(Request& request, - resource_key_t resource_key, - time_t duration) + resource_key_t resource_key, + time_t duration) { - reset(false); - - DynamicRequest& dyn_request = dynamic_cast(request); - - StaticSubRequest* core = new StaticSubRequest(resource_key, duration); - DynamicSubRequest* subreq = new DynamicSubRequest(core, &dyn_request); + reset(false); - dyn_request.get_subrequests().push_back(subreq); + DynamicRequest& dyn_request = dynamic_cast(request); - notify_change(); - return *subreq; + StaticSubRequest* core = new StaticSubRequest(resource_key, duration); + DynamicSubRequest* subreq = new DynamicSubRequest(core, &dyn_request); + + dyn_request.get_subrequests().push_back(subreq); + + notify_change(); + return *subreq; } void ConcreteHistory::reset(bool notify) { - assert(_snapshots.size() > 0); - Snapshots::iterator it = _snapshots.begin(); - it++; // Skip first environment that we saved - - for_each(it, _snapshots.end(), deletor()); - _snapshots.resize(1); // Truncate to keep only our "model" + assert(_snapshots.size() > 0); + Snapshots::iterator it = _snapshots.begin(); + it++; // Skip first environment that we saved - if(notify) - notify_change(); + for_each(it, _snapshots.end(), deletor()); + _snapshots.resize(1); // Truncate to keep only our "model" + + if (notify) + notify_change(); } void ConcreteHistory::notify_change() { - History::RegisteredObservers::iterator it; - for(it =_observers.begin(); it != _observers.end(); it++) - (*it)->update(*this); + History::RegisteredObservers::iterator it; + for (it = _observers.begin(); it != _observers.end(); it++) + (*it)->update(*this); } diff --git a/src/backend/concrete_history.hh b/src/backend/concrete_history.hh index ef668cf..fbda2e2 100644 --- a/src/backend/concrete_history.hh +++ b/src/backend/concrete_history.hh @@ -49,53 +49,54 @@ namespace sgpem ConcreteHistory(const ConcreteHistory&); virtual ~ConcreteHistory(); - virtual void append_new_environment(ConcreteEnvironment* environment); - virtual size_t get_size() const; - virtual const ConcreteEnvironment& get_last_environment() const; - virtual const ConcreteEnvironment& get_environment_at(position index) const throw(std::out_of_range); - - virtual void remove(resource_key_t resource_key); - virtual void remove(Process& process); - virtual void remove(Thread& thread); - virtual void remove(Request& request); - virtual void remove(SubRequest& subrequest); + virtual void append_new_environment(ConcreteEnvironment* environment); + virtual size_t get_size() const; + virtual const ConcreteEnvironment& get_last_environment() const; + virtual const ConcreteEnvironment& get_environment_at(position index) const throw(std::out_of_range); + + virtual void remove(resource_key_t resource_key); + virtual void remove(Process& process); + virtual void remove(Thread& thread); + virtual void remove(Request& request); + virtual void remove(SubRequest& subrequest); - virtual ResourcePair add_resource(const Glib::ustring& name, - bool preemptable = false, - size_t places = 1, - size_t availability = 0); + virtual ResourcePair add_resource(const Glib::ustring& name, + bool preemptable = false, + size_t places = 1, + size_t availability = 0); - virtual DynamicProcess& add_process(const Glib::ustring& name, - time_t arrival_time, - prio_t base_priority = 0); + virtual DynamicProcess& add_process(const Glib::ustring& name, + time_t arrival_time, + prio_t base_priority = 0); - virtual DynamicThread& add_thread(const Glib::ustring& name, - Process& parent, - time_t cpu_time, - time_t arrival_time = 0, - prio_t base_priority = 0); + virtual DynamicThread& add_thread(const Glib::ustring& name, + Process& parent, + time_t cpu_time, + time_t arrival_time = 0, + prio_t base_priority = 0); - virtual DynamicRequest& add_request(Thread& owner, - time_t instant); + virtual DynamicRequest& add_request(Thread& owner, + time_t instant); - virtual DynamicSubRequest& add_subrequest(Request& request, - resource_key_t resource_key, - time_t duration); + virtual DynamicSubRequest& add_subrequest(Request& request, + resource_key_t resource_key, + time_t duration); - virtual void reset(bool notify = true); - - protected: - typedef std::vector Snapshots; - Snapshots _snapshots; + virtual void reset(bool notify = true); - virtual void notify_change(); - - private: - // Disable assignment, implement it only if needed - ConcreteHistory& operator=(const ConcreteHistory& op2); - - }; //~ class ConcreteHistory + protected: + typedef std::vector Snapshots; + Snapshots _snapshots; + + virtual void notify_change(); + + private: + // Disable assignment, implement it only if needed + ConcreteHistory& operator=(const ConcreteHistory& op2); + + } + ; //~ class ConcreteHistory }//~ namespace sgpem diff --git a/src/backend/concrete_simulation.cc b/src/backend/concrete_simulation.cc index 4a8c71b..9bf053a 100644 --- a/src/backend/concrete_simulation.cc +++ b/src/backend/concrete_simulation.cc @@ -32,8 +32,8 @@ using namespace sgpem; using namespace memory; using Glib::usleep; -ConcreteSimulation::ConcreteSimulation() : - _state(state_stopped), _mode(true), _timer_interval(1000), _policy(NULL) +ConcreteSimulation::ConcreteSimulation() : + _state(state_stopped), _mode(true), _timer_interval(1000), _policy(NULL) {} void @@ -75,7 +75,7 @@ ConcreteSimulation::stop() void ConcreteSimulation::run() throw(UserInterruptException, NullPolicyException) { - switch(_state) + switch (_state) { case state_running: return; @@ -88,57 +88,57 @@ ConcreteSimulation::run() throw(UserInterruptException, NullPolicyException) _state = state_running; - if(get_policy() == NULL) - { - stop(); - throw NullPolicyException("no policy selected"); - } - + if (get_policy() == NULL) + { + stop(); + throw NullPolicyException("no policy selected"); + } + //******* CONTINUOUS TIME if (_mode) { do + { + try { - try - { - //step forward - bool yet_to_finish = Scheduler::get_instance().step_forward(_history, *get_policy()); - if(!yet_to_finish) stop(); - - //sleep - Glib::usleep(_timer_interval*1000); - } - catch(UserInterruptException e) - { - stop(); - throw; - } - - //check the state - if (_state == state_stopped || _state == state_paused) - return; + //step forward + bool yet_to_finish = Scheduler::get_instance().step_forward(_history, *get_policy()); + if (!yet_to_finish) stop(); + + //sleep + Glib::usleep(_timer_interval*1000); } - while(true); + catch (UserInterruptException e) + { + stop(); + throw; + } + + //check the state + if (_state == state_stopped || _state == state_paused) + return; + } + while (true); } - + //******* STEP by STEP else { try - { - assert(get_policy() != NULL); - //step forward - bool yet_to_finish = Scheduler::get_instance().step_forward(_history, *get_policy()); - if(yet_to_finish) - pause(); - else - stop(); - } - catch(UserInterruptException e) - { + { + assert(get_policy() != NULL); + //step forward + bool yet_to_finish = Scheduler::get_instance().step_forward(_history, *get_policy()); + if (yet_to_finish) + pause(); + else stop(); - throw; - } + } + catch (UserInterruptException e) + { + stop(); + throw; + } } } @@ -158,8 +158,8 @@ void ConcreteSimulation::set_policy(CPUPolicy* p) { _policy = p; - - if(p != NULL) + + if (p != NULL) CPUPoliciesGatekeeper::get_instance().activate_policy(&_history, p); } diff --git a/src/backend/concrete_simulation.hh b/src/backend/concrete_simulation.hh index b07217e..e83e194 100644 --- a/src/backend/concrete_simulation.hh +++ b/src/backend/concrete_simulation.hh @@ -42,7 +42,7 @@ namespace sgpem void set_timer(const unsigned int); int get_timer() const; - + void set_mode(const bool&); bool get_mode() const; diff --git a/src/backend/cpu_policies_gatekeeper.cc b/src/backend/cpu_policies_gatekeeper.cc index 1022522..56659b1 100644 --- a/src/backend/cpu_policies_gatekeeper.cc +++ b/src/backend/cpu_policies_gatekeeper.cc @@ -55,7 +55,7 @@ CPUPoliciesGatekeeper::register_manager(CPUPolicyManager* manager) ManagerIterator end = _registered.end(); - if(find(_registered.begin(), end, manager) == end) + if (find(_registered.begin(), end, manager) == end) _registered.push_back(manager); } @@ -67,7 +67,7 @@ CPUPoliciesGatekeeper::unregister_manager(CPUPolicyManager* manager) ManagerIterator end = _registered.end(); ManagerIterator pos = find(_registered.begin(), end, manager); - if(pos != end) + if (pos != end) { deactivate_policies(*pos); _registered.erase(pos); @@ -81,7 +81,7 @@ CPUPoliciesGatekeeper::get_current_policy(History* history) throw(runtime_error) ActiveIterator policy = _active_policies.find(history); - if(policy == _active_policies.end()) + if (policy == _active_policies.end()) throw runtime_error("No active policy associated with this " "history is available."); @@ -96,10 +96,10 @@ CPUPoliciesGatekeeper::activate_policy(History *history, CPUPolicy* policy) ActiveIterator end = _active_policies.end(); ActiveIterator pos = _active_policies.find(history); - if(pos != end && pos->second != policy) + if (pos != end && pos->second != policy) _active_policies[history]->deactivate(); - if(pos == end || pos->second != policy) + if (pos == end || pos->second != policy) { _active_policies[history] = policy; _active_policies[history]->activate(); @@ -119,23 +119,23 @@ CPUPoliciesGatekeeper::deactivate_policies(CPUPolicyManager* manager) CPUPolicyIterator avail_it = avail_policies.begin(); CPUPolicyIterator avail_end = avail_policies.end(); - for(; avail_it != avail_end; ++avail_it) + for (; avail_it != avail_end; ++avail_it) { // TODO isn't there a way to write more compact code by using // library utilities? ActiveIterator act_it = _active_policies.begin(); - while(act_it != _active_policies.end()) - { - if(act_it->second == *avail_it) - { - ActiveIterator removable = act_it++; - removable->second->deactivate(); - _active_policies.erase(removable); - } - else - act_it++; - } + while (act_it != _active_policies.end()) + { + if (act_it->second == *avail_it) + { + ActiveIterator removable = act_it++; + removable->second->deactivate(); + _active_policies.erase(removable); + } + else + act_it++; + } } //~ for(avail_it) } diff --git a/src/backend/cpu_policy_manager.cc b/src/backend/cpu_policy_manager.cc index 9a89eff..ed8e15c 100644 --- a/src/backend/cpu_policy_manager.cc +++ b/src/backend/cpu_policy_manager.cc @@ -38,7 +38,7 @@ CPUPolicyManager::~CPUPolicyManager() { // This check is necessary: //FIXME remove this when get_registered_manager is dropped - if(_registered == this) _registered = NULL; + if (_registered == this) _registered = NULL; CPUPoliciesGatekeeper::get_instance().unregister_manager(this); } diff --git a/src/backend/dynamic_process.cc b/src/backend/dynamic_process.cc index 869cbce..3d17872 100644 --- a/src/backend/dynamic_process.cc +++ b/src/backend/dynamic_process.cc @@ -32,28 +32,28 @@ using namespace sgpem; using namespace std; -DynamicProcess::DynamicProcess(StaticProcess* core) : - DynamicSchedulable(), _core(core) +DynamicProcess::DynamicProcess(StaticProcess* core) : + DynamicSchedulable(), _core(core) { assert(core != NULL); } DynamicProcess::DynamicProcess(const DynamicProcess &other) : - Schedulable(), DynamicSchedulable(other), Process(), - _core(other._core) + Schedulable(), DynamicSchedulable(other), Process(), + _core(other._core) { typedef vector::const_iterator ThreadIt; const vector& other_threads = other._dynamic_threads; - for(ThreadIt it = other_threads.begin(); it != other_threads.end(); ++it) + for (ThreadIt it = other_threads.begin(); it != other_threads.end(); ++it) new DynamicThread(*(*it), this); } DynamicProcess::~DynamicProcess() { - for_each(_dynamic_threads.begin(), _dynamic_threads.end(), - memory::deletor()); + for_each(_dynamic_threads.begin(), _dynamic_threads.end(), + memory::deletor()); } std::vector @@ -65,71 +65,71 @@ DynamicProcess::get_threads() std::vector DynamicProcess::get_threads() const { - return vector(_dynamic_threads.begin(), _dynamic_threads.end()); + return vector(_dynamic_threads.begin(), _dynamic_threads.end()); } Schedulable::state DynamicProcess::get_state() const { - int total = _dynamic_threads.size(); - int running = 0; - int ready = 0; - int blocked = 0; - int terminated = 0; - int future = 0; + int total = _dynamic_threads.size(); + int running = 0; + int ready = 0; + int blocked = 0; + int terminated = 0; + int future = 0; - unsigned int closest = 0; - - vector::const_iterator it = _dynamic_threads.begin(); - for(; it != _dynamic_threads.end(); it++) - { - if ((**it).get_state() == state_running) running++; - if ((**it).get_state() == state_ready) ready++; - if ((**it).get_state() == state_blocked) blocked++; - if ((**it).get_state() == state_terminated) terminated++; - if ((**it).get_state() == state_future) - { - unsigned int arrival = (**it).get_arrival_time(); - // if this is the first future occurrence, record its arrival; - // else record its arrival if and only if it is smaller then the recorded one - if (future == 0) - closest = arrival; - else - closest = (closest < arrival) ? closest : arrival; - future++; - } - } + unsigned int closest = 0; - assert(total > 0); - assert(running == 1 || running == 0); - assert(running + ready + blocked + terminated + future == total); + vector::const_iterator it = _dynamic_threads.begin(); + for (; it != _dynamic_threads.end(); it++) + { + if ((**it).get_state() == state_running) running++; + if ((**it).get_state() == state_ready) ready++; + if ((**it).get_state() == state_blocked) blocked++; + if ((**it).get_state() == state_terminated) terminated++; + if ((**it).get_state() == state_future) + { + unsigned int arrival = (**it).get_arrival_time(); + // if this is the first future occurrence, record its arrival; + // else record its arrival if and only if it is smaller then the recorded one + if (future == 0) + closest = arrival; + else + closest = (closest < arrival) ? closest : arrival; + future++; + } + } - if (running > 0) - return state_running; - if (ready > 0) // running == 0 - return state_ready; - if (blocked > 0) // running == 0 && ready == 0 - return state_blocked; - // Now check if a "hole" happens: if all threads are terminated - // or blocked the next - // thread to start, e.g. the one with the least arrival_time, has - // start time greater than the current process elapsed time, then - // pass from state_future to state_terminated: - if (closest > get_elapsed_time()) - return state_terminated; - if (terminated > 0) // running == 0 && ready == 0 && blocked == 0 - return state_terminated; - if (future > 0) // running == 0 && ready == 0 && blocked == 0 && terminated == 0 - return state_future; + assert(total > 0); + assert(running == 1 || running == 0); + assert(running + ready + blocked + terminated + future == total); - // I'm not sure if we can get here (maybe if there are no threads?), - // but I don't like this compiler warning: 'control reaches end of non-void function' + if (running > 0) + return state_running; + if (ready > 0) // running == 0 + return state_ready; + if (blocked > 0) // running == 0 && ready == 0 + return state_blocked; + // Now check if a "hole" happens: if all threads are terminated + // or blocked the next + // thread to start, e.g. the one with the least arrival_time, has + // start time greater than the current process elapsed time, then + // pass from state_future to state_terminated: + if (closest > get_elapsed_time()) + return state_terminated; + if (terminated > 0) // running == 0 && ready == 0 && blocked == 0 + return state_terminated; + if (future > 0) // running == 0 && ready == 0 && blocked == 0 && terminated == 0 return state_future; - - // Since premature optimization is the root of all evil, and the - // following code was very fast but also very wrong, the coder - // will be punished by allowing her to code in C++ just after - // having passed "Algoritmi 3" exam with full marks. + + // I'm not sure if we can get here (maybe if there are no threads?), + // but I don't like this compiler warning: 'control reaches end of non-void function' + return state_future; + + // Since premature optimization is the root of all evil, and the + // following code was very fast but also very wrong, the coder + // will be punished by allowing her to code in C++ just after + // having passed "Algoritmi 3" exam with full marks. /* typedef vector::const_iterator ThreadIt; @@ -164,7 +164,7 @@ DynamicProcess::get_state() const // TODO Is this OK? Must be tested... - + int thread_starts_at; switch(thread_state) { @@ -189,8 +189,8 @@ DynamicProcess::get_state() const } } //~ "for" iterating over threads - // reused hole checking system - */ + // reused hole checking system + */ } @@ -204,32 +204,32 @@ DynamicProcess::serialize(SerializeVisitor& translator) const StaticProcess& DynamicProcess::get_core() { - return *_core; + return *_core; } const StaticProcess& DynamicProcess::get_core() const { - return *_core; + return *_core; } std::vector& DynamicProcess::get_dynamic_threads() { - return _dynamic_threads; + return _dynamic_threads; } unsigned int DynamicProcess::get_elapsed_time() const { unsigned int result = 0; - for(std::vector::const_iterator it = _dynamic_threads.begin(); - it != _dynamic_threads.end(); it++) - { - result += (*it)->get_elapsed_time(); - } + for (std::vector::const_iterator it = _dynamic_threads.begin(); + it != _dynamic_threads.end(); it++) + { + result += (*it)->get_elapsed_time(); + } return result; } @@ -237,13 +237,13 @@ int DynamicProcess::get_last_acquisition() const { int result = -1; - for(std::vector::const_iterator it = _dynamic_threads.begin(); - it != _dynamic_threads.end(); it++) - { - int acq = (*it)->get_last_acquisition(); - if(result < acq) - result = acq; - } + for (std::vector::const_iterator it = _dynamic_threads.begin(); + it != _dynamic_threads.end(); it++) + { + int acq = (*it)->get_last_acquisition(); + if (result < acq) + result = acq; + } return result; } @@ -251,13 +251,13 @@ int DynamicProcess::get_last_release() const { int result = -1; - for(std::vector::const_iterator it = _dynamic_threads.begin(); - it != _dynamic_threads.end(); it++) - { - int acq = (*it)->get_last_release(); - if(result < acq) - result = acq; - } + for (std::vector::const_iterator it = _dynamic_threads.begin(); + it != _dynamic_threads.end(); it++) + { + int acq = (*it)->get_last_release(); + if (result < acq) + result = acq; + } return result; } diff --git a/src/backend/dynamic_process.hh b/src/backend/dynamic_process.hh index 3c2928e..782b84d 100644 --- a/src/backend/dynamic_process.hh +++ b/src/backend/dynamic_process.hh @@ -45,7 +45,7 @@ namespace sgpem public: DynamicProcess(StaticProcess* core); DynamicProcess(const DynamicProcess &other); - virtual ~DynamicProcess(); + virtual ~DynamicProcess(); std::vector get_threads(); std::vector get_threads() const; @@ -61,8 +61,8 @@ namespace sgpem virtual StaticProcess& get_core(); virtual const StaticProcess& get_core() const; - // Does also the job of "add_thread" and "remove_thread" - std::vector& get_dynamic_threads(); + // Does also the job of "add_thread" and "remove_thread" + std::vector& get_dynamic_threads(); private: memory::smart_ptr _core; diff --git a/src/backend/dynamic_request.cc b/src/backend/dynamic_request.cc index 8def5f2..99ff19d 100644 --- a/src/backend/dynamic_request.cc +++ b/src/backend/dynamic_request.cc @@ -47,38 +47,38 @@ DynamicRequest::DynamicRequest(StaticRequest *core, } DynamicRequest::DynamicRequest(const DynamicRequest& other, DynamicThread* owner) : - _static_request(other._static_request), _dynamic_thread(owner) + _static_request(other._static_request), _dynamic_thread(owner) { typedef vector SubReqVec; assert(owner != NULL); const SubReqVec& other_subs = other._dynamic_subrequests; - + // Not sure of this, but the constructor of DynamicSubRequest should take care - // of adding itself to the vector of sub requests. This is only my opinion, + // of adding itself to the vector of sub requests. This is only my opinion, // but I think this is a complicated way of doing things... - for(SubReqVec::const_iterator it = other_subs.begin(); it != other_subs.end(); ++it) + for (SubReqVec::const_iterator it = other_subs.begin(); it != other_subs.end(); ++it) new DynamicSubRequest(*(*it), this); - + // Leave this line: it helps us with a compiler warning if // the get_dynamic* method signature changes: std::vector& siblings = owner->get_dynamic_requests(); siblings.push_back(this); } - + DynamicRequest::~DynamicRequest() { - for_each(_dynamic_subrequests.begin(), _dynamic_subrequests.end(), - memory::deletor()); + for_each(_dynamic_subrequests.begin(), _dynamic_subrequests.end(), + memory::deletor()); } bool DynamicRequest::operator==(const Request& op2) const { - assert(dynamic_cast(&op2) != NULL); + assert(dynamic_cast(&op2) != NULL); return _static_request == dynamic_cast(op2)._static_request; } @@ -112,42 +112,42 @@ DynamicRequest::get_instant() const Request::state DynamicRequest::get_state() const { - typedef std::vector SubReqs; + typedef std::vector SubReqs; + + state result = state_future; - state result = state_future; - #ifndef NDEBUG - // Only for debug: - bool at_least_once = false; + // Only for debug: + bool at_least_once = false; #endif // ~NDEBUG - const SubReqs& sreqs = _dynamic_subrequests; - for(SubReqs::const_iterator it = sreqs.begin(); it != sreqs.end(); it++) - { - SubRequest& cur = **it; + const SubReqs& sreqs = _dynamic_subrequests; + for (SubReqs::const_iterator it = sreqs.begin(); it != sreqs.end(); it++) + { + SubRequest& cur = **it; - switch(cur.get_state()) - { - case state_allocated: - return state_allocated; - case state_unallocable: - return state_unallocable; - default: + switch (cur.get_state()) + { + case state_allocated: + return state_allocated; + case state_unallocable: + return state_unallocable; + default: #ifndef NDEBUG - // We want to be sure that all subrequests - // have the same state since state_allocable, - // state_terminated and state_future are mutually - // exclusive - if(at_least_once) - assert(result == cur.get_state()); - at_least_once = true; + // We want to be sure that all subrequests + // have the same state since state_allocable, + // state_terminated and state_future are mutually + // exclusive + if (at_least_once) + assert(result == cur.get_state()); + at_least_once = true; #endif //~ NDEBUG - result = cur.get_state(); - } - } - return result; + result = cur.get_state(); + } + } + return result; } @@ -161,12 +161,12 @@ DynamicRequest::serialize(SerializeVisitor& translator) const StaticRequest& DynamicRequest::get_core() { - return *_static_request; + return *_static_request; } const StaticRequest& DynamicRequest::get_core() const { - return *_static_request; + return *_static_request; } diff --git a/src/backend/dynamic_request.hh b/src/backend/dynamic_request.hh index 93637cb..d3b952c 100644 --- a/src/backend/dynamic_request.hh +++ b/src/backend/dynamic_request.hh @@ -43,11 +43,11 @@ namespace sgpem public: DynamicRequest(StaticRequest *core, DynamicThread* owner); DynamicRequest(const DynamicRequest& other, DynamicThread* owner); - ~DynamicRequest(); + ~DynamicRequest(); - virtual bool operator==(const Request& op2) const; + virtual bool operator==(const Request& op2) const; - virtual std::vector get_subrequests(); + virtual std::vector get_subrequests(); DynamicThread& get_thread(); @@ -57,12 +57,12 @@ namespace sgpem void serialize(SerializeVisitor& translator) const; - StaticRequest& get_core(); - const StaticRequest& get_core() const; + StaticRequest& get_core(); + const StaticRequest& get_core() const; - // Since this method is visible only by the backend, - // return directly a reference that lets us to - // add and remove subrequests at will. + // Since this method is visible only by the backend, + // return directly a reference that lets us to + // add and remove subrequests at will. std::vector& get_dynamic_subrequests(); private: diff --git a/src/backend/dynamic_resource.cc b/src/backend/dynamic_resource.cc index e42bc82..4922b3d 100644 --- a/src/backend/dynamic_resource.cc +++ b/src/backend/dynamic_resource.cc @@ -36,7 +36,7 @@ DynamicResource::DynamicResource(StaticResource *core) : bool DynamicResource::operator==(const Resource& op2) const { - assert(dynamic_cast(&op2) != NULL); + assert(dynamic_cast(&op2) != NULL); return _static_resource == dynamic_cast(op2)._static_resource; } @@ -62,12 +62,12 @@ DynamicResource::serialize(SerializeVisitor& translator) const StaticResource& DynamicResource::get_core() { - return *_static_resource; + return *_static_resource; } const StaticResource& DynamicResource::get_core() const { - return *_static_resource; + return *_static_resource; } diff --git a/src/backend/dynamic_resource.hh b/src/backend/dynamic_resource.hh index 09401e0..b324fdd 100644 --- a/src/backend/dynamic_resource.hh +++ b/src/backend/dynamic_resource.hh @@ -39,15 +39,15 @@ namespace sgpem public: DynamicResource(StaticResource *core); - virtual bool operator==(const Resource& op2) const; + virtual bool operator==(const Resource& op2) const; Glib::ustring get_name() const; unsigned int get_places() const; void serialize(SerializeVisitor& translator) const; - StaticResource& get_core(); - const StaticResource& get_core() const; + StaticResource& get_core(); + const StaticResource& get_core() const; private: memory::smart_ptr _static_resource; diff --git a/src/backend/dynamic_schedulable.cc b/src/backend/dynamic_schedulable.cc index d22fb8f..21995b5 100644 --- a/src/backend/dynamic_schedulable.cc +++ b/src/backend/dynamic_schedulable.cc @@ -27,14 +27,14 @@ using namespace sgpem; using namespace std; -DynamicSchedulable::DynamicSchedulable() - : _priority_push(0) +DynamicSchedulable::DynamicSchedulable() + : _priority_push(0) {} bool DynamicSchedulable::operator==(const Schedulable& op2) const { - assert(dynamic_cast(&op2) != NULL); + assert(dynamic_cast(&op2) != NULL); return &get_core() == &(dynamic_cast(op2).get_core()); } @@ -62,7 +62,7 @@ DynamicSchedulable::get_total_cpu_time() const return get_core().get_total_cpu_time(); } -int +int DynamicSchedulable::set_priority_push(int new_value) { int old_priority_push = _priority_push; diff --git a/src/backend/dynamic_sub_request.cc b/src/backend/dynamic_sub_request.cc index 02fb13f..002644f 100644 --- a/src/backend/dynamic_sub_request.cc +++ b/src/backend/dynamic_sub_request.cc @@ -30,42 +30,41 @@ using namespace sgpem; -DynamicSubRequest::DynamicSubRequest(StaticSubRequest* core, - DynamicRequest* owner) : - _static_subrequest(core), _owner(owner), - _queue_position(-1), _ran_for(0), _state(Request::state_future) +DynamicSubRequest::DynamicSubRequest(StaticSubRequest* core, + DynamicRequest* owner) : + _static_subrequest(core), _owner(owner), + _queue_position(-1), _ran_for(0), _state(Request::state_future) { assert(core != NULL); assert(owner != NULL); - // Leave this line: it helps us with a compiler warning if - // the get_dynamic* method signature changes: - std::vector& siblings = owner->get_dynamic_subrequests(); - siblings.push_back(this); +// Leave this line: it helps us with a compiler warning if +// the get_dynamic* method signature changes: + std::vector& siblings = owner->get_dynamic_subrequests(); + siblings.push_back(this); } -DynamicSubRequest::DynamicSubRequest(const DynamicSubRequest& other, +DynamicSubRequest::DynamicSubRequest(const DynamicSubRequest& other, DynamicRequest* owner) : - _static_subrequest(other._static_subrequest), _owner(owner), - _queue_position(other._queue_position), _ran_for(other._ran_for), - _state(other._state) + _static_subrequest(other._static_subrequest), _owner(owner), + _queue_position(other._queue_position), _ran_for(other._ran_for), + _state(other._state) { assert(owner != NULL); - - // Leave this line: it helps us with a compiler warning if - // the get_dynamic* method signature changes: - std::vector& siblings = owner->get_dynamic_subrequests(); - siblings.push_back(this); + +// Leave this line: it helps us with a compiler warning if +// the get_dynamic* method signature changes: + std::vector& siblings = owner->get_dynamic_subrequests(); + siblings.push_back(this); } DynamicSubRequest::~DynamicSubRequest() -{ -} +{} bool DynamicSubRequest::operator==(const SubRequest& op2) const { - assert(dynamic_cast(&op2) != NULL); + assert(dynamic_cast(&op2) != NULL); return _static_subrequest == dynamic_cast(op2)._static_subrequest; } @@ -99,42 +98,42 @@ DynamicSubRequest::set_queue_position(int position) DynamicRequest& DynamicSubRequest::get_request() { - return *_owner; + return *_owner; } DynamicSubRequest::state DynamicSubRequest::get_state() const { - return _state; + return _state; } DynamicSubRequest::state DynamicSubRequest::set_state(state new_state) { - state temp = _state; - _state = new_state; - return temp; + state temp = _state; + _state = new_state; + return temp; } -unsigned int +unsigned int DynamicSubRequest::get_remaining_time() const { - return _static_subrequest->get_length() - _ran_for; + return _static_subrequest->get_length() - _ran_for; } unsigned int DynamicSubRequest::decrease_remaining_time() { - assert(_state == Request::state_allocated); - unsigned int temp = get_remaining_time(); - if(temp > 0) - _ran_for++; - - return temp; + assert(_state == Request::state_allocated); + unsigned int temp = get_remaining_time(); + if (temp > 0) + _ran_for++; + + return temp; } @@ -145,15 +144,15 @@ DynamicSubRequest::serialize(SerializeVisitor& translator) const } -StaticSubRequest& +StaticSubRequest& DynamicSubRequest::get_core() { - return *_static_subrequest; + return *_static_subrequest; } -const StaticSubRequest& +const StaticSubRequest& DynamicSubRequest::get_core() const { - return *_static_subrequest; + return *_static_subrequest; } diff --git a/src/backend/dynamic_sub_request.hh b/src/backend/dynamic_sub_request.hh index 1b325c6..814c795 100644 --- a/src/backend/dynamic_sub_request.hh +++ b/src/backend/dynamic_sub_request.hh @@ -34,20 +34,20 @@ namespace sgpem { class DynamicSubRequest; - class SerializeVisitor; + class SerializeVisitor; class Resource; class StaticSubRequest; class SG_DLLLOCAL DynamicSubRequest : public SubRequest { - public: - DynamicSubRequest(StaticSubRequest* core, - DynamicRequest* owner); + public: + DynamicSubRequest(StaticSubRequest* core, + DynamicRequest* owner); DynamicSubRequest(const DynamicSubRequest& other, DynamicRequest* owner); - virtual ~DynamicSubRequest(); + virtual ~DynamicSubRequest(); - virtual bool operator==(const SubRequest& op2) const; + virtual bool operator==(const SubRequest& op2) const; resource_key_t get_resource_key() const; @@ -56,28 +56,28 @@ namespace sgpem int get_queue_position() const; void set_queue_position(int position); - virtual DynamicRequest& get_request(); + virtual DynamicRequest& get_request(); - state get_state() const; - state set_state(state new_state); - - unsigned int get_remaining_time() const; - unsigned int decrease_remaining_time(); + state get_state() const; + state set_state(state new_state); + + unsigned int get_remaining_time() const; + unsigned int decrease_remaining_time(); void serialize(SerializeVisitor& translator) const; - StaticSubRequest& get_core(); - const StaticSubRequest& get_core() const; + StaticSubRequest& get_core(); + const StaticSubRequest& get_core() const; private: // Undefined DynamicSubRequest(const DynamicSubRequest&); memory::smart_ptr _static_subrequest; - DynamicRequest* _owner; + DynamicRequest* _owner; int _queue_position; - unsigned int _ran_for; - state _state; + unsigned int _ran_for; + state _state; }; } diff --git a/src/backend/dynamic_thread.cc b/src/backend/dynamic_thread.cc index 2b8f636..5616cb9 100644 --- a/src/backend/dynamic_thread.cc +++ b/src/backend/dynamic_thread.cc @@ -34,32 +34,32 @@ using namespace sgpem; using namespace std; -DynamicThread::DynamicThread(StaticThread* core, DynamicProcess* parent) - : DynamicSchedulable(), _core(core), _state(state_future), _parent(parent), +DynamicThread::DynamicThread(StaticThread* core, DynamicProcess* parent) + : DynamicSchedulable(), _core(core), _state(state_future), _parent(parent), _ran_for(0), _last_acquisition(-1), _last_release(-1) { - assert(core != NULL); - assert(parent != NULL); - - // Leave this line: it helps us with a compiler warning if - // the get_dynamic* method signature changes: - std::vector& siblings = parent->get_dynamic_threads(); - siblings.push_back(this); + assert(core != NULL); + assert(parent != NULL); + + // Leave this line: it helps us with a compiler warning if + // the get_dynamic* method signature changes: + std::vector& siblings = parent->get_dynamic_threads(); + siblings.push_back(this); } DynamicThread::DynamicThread(const DynamicThread &other, DynamicProcess* parent) : - Schedulable(), DynamicSchedulable(other), Thread(), - _core(other._core), _state(other._state), _parent(parent), - _ran_for(other._ran_for), _last_acquisition(other._last_acquisition), + Schedulable(), DynamicSchedulable(other), Thread(), + _core(other._core), _state(other._state), _parent(parent), + _ran_for(other._ran_for), _last_acquisition(other._last_acquisition), _last_release(other._last_release) { typedef vector::const_iterator ReqIt; assert(parent != NULL); - + const vector& other_req = other._dynamic_requests; - for(ReqIt it = other_req.begin(); it != other_req.end(); ++it) + for (ReqIt it = other_req.begin(); it != other_req.end(); ++it) new DynamicRequest(*(*it), this); // Leave this line: it helps us with a compiler warning if @@ -70,8 +70,8 @@ DynamicThread::DynamicThread(const DynamicThread &other, DynamicProcess* parent) DynamicThread::~DynamicThread() { - for_each(_dynamic_requests.begin(), _dynamic_requests.end(), - memory::deletor()); + for_each(_dynamic_requests.begin(), _dynamic_requests.end(), + memory::deletor()); } @@ -112,20 +112,20 @@ DynamicThread::serialize(SerializeVisitor& translator) const StaticThread& DynamicThread::get_core() { - return *_core; + return *_core; } const StaticThread& DynamicThread::get_core() const { - return *_core; + return *_core; } std::vector& DynamicThread::get_dynamic_requests() { - return _dynamic_requests; + return _dynamic_requests; } @@ -138,10 +138,10 @@ DynamicThread::get_elapsed_time() const void DynamicThread::decrease_remaining_time() { - // strict check for us to better debug scheduler - assert(_ran_for < get_total_cpu_time()); - if(_ran_for < get_total_cpu_time()) - _ran_for++; + // strict check for us to better debug scheduler + assert(_ran_for < get_total_cpu_time()); + if (_ran_for < get_total_cpu_time()) + _ran_for++; } int diff --git a/src/backend/dynamic_thread.hh b/src/backend/dynamic_thread.hh index 21573ca..25a5a52 100644 --- a/src/backend/dynamic_thread.hh +++ b/src/backend/dynamic_thread.hh @@ -72,9 +72,9 @@ namespace sgpem std::vector& get_dynamic_requests(); private: - // Undefined + // Undefined DynamicThread(const DynamicThread &other); - + memory::smart_ptr _core; state _state; std::vector _dynamic_requests; diff --git a/src/backend/environment.hh b/src/backend/environment.hh index 0fd7df7..d929bea 100644 --- a/src/backend/environment.hh +++ b/src/backend/environment.hh @@ -38,7 +38,7 @@ namespace sgpem /// \brief An instant of the simulation. /// An object of the Environment class represents a snapshot of - /// the simulated environment taken in a fixed instant, composed + /// the simulated environment taken in a fixed instant, composed /// by processes, threads, resources and more. /// A snapshot for every single entity is accessible from here. /// All the provided objects and data is constant. @@ -58,11 +58,11 @@ namespace sgpem class SG_DLLEXPORT Environment { public: - typedef SubRequest::resource_key_t resource_key_t; + typedef SubRequest::resource_key_t resource_key_t; - typedef std::vector Processes; - typedef std::map Resources; - typedef std::vector SubRequestQueue; + typedef std::vector Processes; + typedef std::map Resources; + typedef std::vector SubRequestQueue; /// \brief Returns an indexed set of snapshots of the processes /// Returns a standard vector of Process objects describing @@ -72,7 +72,7 @@ namespace sgpem /// \return a constant set of snapshots of processes virtual const Processes& - get_processes() const = 0; + get_processes() const = 0; /// \brief Returns an indexed set of snapshots of the resources @@ -90,7 +90,7 @@ namespace sgpem /// \return an indexed constant set of snapshot of resources. virtual const Resources& - get_resources() const = 0; + get_resources() const = 0; /// \brief Returns a snapshot of the current request queue for a resource. @@ -101,7 +101,7 @@ namespace sgpem /// \return the current ready requests queue (constant). virtual const SubRequestQueue& - get_request_queue(resource_key_t resource_key) const = 0; + get_request_queue(resource_key_t resource_key) const = 0; /// \brief Returns a snapshot of the current scheduler's ready queue. @@ -112,7 +112,7 @@ namespace sgpem /// \return the current ready queue (constant). virtual const ReadyQueue& - get_sorted_queue() const = 0; + get_sorted_queue() const = 0; /// \brief The standard virtual destructor. diff --git a/src/backend/global_preferences.cc b/src/backend/global_preferences.cc index eefcb78..21ce6ea 100644 --- a/src/backend/global_preferences.cc +++ b/src/backend/global_preferences.cc @@ -96,13 +96,13 @@ GlobalPreferences::get_plugin_dirs() return _mod_dirs; } -int +int GlobalPreferences::get_speed() { return _speed; } -int +int GlobalPreferences::set_speed(int new_speed) { int old_speed = _speed; @@ -123,7 +123,7 @@ void GlobalPreferences::load_configrc() { KeyFile kf; - + kf.file_read(get_config_filename()); key_file_read(kf); } @@ -141,7 +141,7 @@ void GlobalPreferences::load_configrc(std::istream &is) { KeyFile kf; - + kf.file_read(is); key_file_read(kf); } @@ -157,7 +157,8 @@ GlobalPreferences::key_file_read(KeyFile& kf) { int new_speed; const Glib::ustring* val = kf.search_value(Glib::ustring("speed")); - if(val){ + if (val) + { string_to_int(*val, new_speed); set_speed(new_speed); } @@ -165,18 +166,18 @@ GlobalPreferences::key_file_read(KeyFile& kf) // read modules directories { const Glib::ustring* val = kf.search_value(Glib::ustring("modules-dir-number")); - if(val) + if (val) { std::istringstream istr(val->c_str()); int n; istr >> n; - for(int i=1; i<=n; i++) + for (int i = 1; i <= n; i++) { std::ostringstream ostr; ostr << "modules-dir-" << i; Glib::ustring key(ostr.str()); val = kf.search_value(key); - if(val) + if (val) { // add_modules_dir(*val); _mod_dirs.push_back(*val); @@ -188,18 +189,18 @@ GlobalPreferences::key_file_read(KeyFile& kf) // read policies directories { const Glib::ustring* val = kf.search_value(Glib::ustring("policies-dir-number")); - if(val) + if (val) { std::istringstream istr(val->c_str()); int n; istr >> n; - for(int i=1; i<=n; i++) + for (int i = 1; i <= n; i++) { std::ostringstream ostr; - ostr << "policies-dir-" << i; + ostr << "policies-dir-" << i; Glib::ustring key(ostr.str()); val = kf.search_value(key); - if(val) + if (val) { // add_policies_dir(*val); _pol_dirs.push_back(*val); @@ -227,10 +228,11 @@ GlobalPreferences::key_file_write(KeyFile& kf) /* GlobalPreferences::dir_iterator iter=_globalPreferences.modules_dir_begin(); */ - dir_iterator iter=_mod_dirs.begin(); - dir_iterator end=_mod_dirs.end(); - int n=0; - while(iter!=end){ + dir_iterator iter = _mod_dirs.begin(); + dir_iterator end = _mod_dirs.end(); + int n = 0; + while (iter != end) + { std::ostringstream ostr; n++; ostr << "modules-dir-" << n; // << std::ends; @@ -246,13 +248,14 @@ GlobalPreferences::key_file_write(KeyFile& kf) } // add policies directories { -/* - GlobalPreferences::dir_iterator iter=_globalPreferences.policies_dir_begin(); - */ - dir_iterator iter=_pol_dirs.begin(); - dir_iterator end=_pol_dirs.end(); - int n=0; - while(iter!=end){ + /* + GlobalPreferences::dir_iterator iter=_globalPreferences.policies_dir_begin(); + */ + dir_iterator iter = _pol_dirs.begin(); + dir_iterator end = _pol_dirs.end(); + int n = 0; + while (iter != end) + { std::ostringstream ostr; n++; ostr << "policies-dir-" << n; // << std::ends; diff --git a/src/backend/global_preferences.hh b/src/backend/global_preferences.hh index a5a4791..a0fca04 100644 --- a/src/backend/global_preferences.hh +++ b/src/backend/global_preferences.hh @@ -49,25 +49,25 @@ namespace sgpem public: typedef std::vector::const_iterator dir_iterator; - + dir_iterator modules_dir_begin() const; dir_iterator modules_dir_end() const; dir_iterator policies_dir_begin() const; dir_iterator policies_dir_end() const; - + /** \return GlobalPreferences configuration filename */ const Glib::ustring get_config_filename(); - + /** \brief Adds a directory search entry to modules dirs */ void add_modules_dir(const Glib::ustring& moddir); - + /** \brief Adds a directory search entry to policies dirs */ @@ -75,14 +75,14 @@ namespace sgpem /** \brief Returns configured Policy directories - + \return ::_policy_dirs */ std::vector& get_policy_dirs(); - + /** \brief Returns configured Plugin directories - + \return ::_plugin_dirs */ std::vector& get_plugin_dirs(); @@ -93,14 +93,14 @@ namespace sgpem \return _speed */ int get_speed(); - + /** \brief Returns the simumulation speed and return old speed \return _speed */ int set_speed(int new_speed); - + /** \brief Writes preferences to disk @@ -122,7 +122,7 @@ namespace sgpem \throw std::io_error */ void load_configrc(); - + void write_configrc(std::ostream &os); void load_configrc(std::istream &is); private: @@ -148,7 +148,7 @@ namespace sgpem -# Via command line arguments -# By a backend::Plugin::on_init() method called when loading an external DSO. This is perfectly normal and permitted. */ - + int _speed; }; } diff --git a/src/backend/global_preferences_serializer.cc b/src/backend/global_preferences_serializer.cc index 3c9f97b..8bfb461 100644 --- a/src/backend/global_preferences_serializer.cc +++ b/src/backend/global_preferences_serializer.cc @@ -27,11 +27,11 @@ namespace sgpem { GlobalPreferencesSerializer::GlobalPreferencesSerializer(GlobalPreferences &gp) - : _globalPreferences(gp) + : _globalPreferences(gp) {} - - - + + + void GlobalPreferencesSerializer::file_read(const Glib::ustring& filename) { @@ -41,18 +41,18 @@ namespace sgpem // read modules directories { const Glib::ustring* val = search_value(Glib::ustring("modules-dir-number")); - if(val) + if (val) { std::istringstream istr(val->c_str()); int n; istr >> n; - for(int i=1; i<=n; i++) + for (int i = 1; i <= n; i++) { std::ostringstream ostr; ostr << "modules-dir-" << i << std::ends; Glib::ustring key(ostr.str()); val = search_value(key); - if(val) + if (val) { _globalPreferences.add_modules_dir(*val); } @@ -63,18 +63,18 @@ namespace sgpem // read policies directories { const Glib::ustring* val = search_value(Glib::ustring("policies-dir-number")); - if(val) + if (val) { std::istringstream istr(val->c_str()); int n; istr >> n; - for(int i=1; i<=n; i++) + for (int i = 1; i <= n; i++) { std::ostringstream ostr; ostr << "policies-dir-" << i << std::ends; Glib::ustring key(ostr.str()); val = search_value(key); - if(val) + if (val) { _globalPreferences.add_policies_dir(*val); } @@ -82,15 +82,16 @@ namespace sgpem } } } - + void GlobalPreferencesSerializer::file_write(const Glib::ustring& filename) { // add modules directories { - GlobalPreferences::dir_iterator iter=_globalPreferences.modules_dir_begin(); - int n=0; - while(iter!=_globalPreferences.modules_dir_end()){ + GlobalPreferences::dir_iterator iter = _globalPreferences.modules_dir_begin(); + int n = 0; + while (iter != _globalPreferences.modules_dir_end()) + { std::ostringstream ostr; n++; ostr << "modules-dir-" << n << std::ends; @@ -106,9 +107,10 @@ namespace sgpem } // add policies directories { - GlobalPreferences::dir_iterator iter=_globalPreferences.policies_dir_begin(); - int n=0; - while(iter!=_globalPreferences.policies_dir_end()){ + GlobalPreferences::dir_iterator iter = _globalPreferences.policies_dir_begin(); + int n = 0; + while (iter != _globalPreferences.policies_dir_end()) + { std::ostringstream ostr; n++; ostr << "policies-dir-" << n << std::ends; @@ -122,7 +124,7 @@ namespace sgpem Glib::ustring value(ostr.str()); insert_key_value(key, value); } - + KeyFile::file_write(filename); } } diff --git a/src/backend/global_preferences_serializer.hh b/src/backend/global_preferences_serializer.hh index 7581c2f..c4ee9ba 100644 --- a/src/backend/global_preferences_serializer.hh +++ b/src/backend/global_preferences_serializer.hh @@ -29,7 +29,7 @@ namespace sgpem class GlobalPreferencesSerializer; - + /** \brief Save and retrieve global preferences formatted as key=value rows. * * This class handles files to store and retrieve global preferences diff --git a/src/backend/history.cc b/src/backend/history.cc index 478f288..5779aed 100644 --- a/src/backend/history.cc +++ b/src/backend/history.cc @@ -30,40 +30,38 @@ using namespace std; History::History() - : _notify(true) -{ -} + : _notify(true) +{} History::~History() -{ -} +{} void History::attach(HistoryObserver& observer) { - _observers.push_back(&observer); + _observers.push_back(&observer); } void History::detach(const HistoryObserver& observer) { - _observers.erase(std::find(_observers.begin(), - _observers.end(), - &observer)); + _observers.erase(std::find(_observers.begin(), + _observers.end(), + &observer)); } -void +void History::notify_change() { - if(!_notify) return; + if (!_notify) return; - for(RegisteredObservers::iterator it =_observers.begin(); - it != _observers.end(); it++) - (*it)->update(*this); + for (RegisteredObservers::iterator it = _observers.begin(); + it != _observers.end(); it++) + (*it)->update(*this); } @@ -72,9 +70,9 @@ History::set_notify_enabled(bool enabled) { bool old_value = _notify; _notify = enabled; - + // Force notify if we re-enable it - if(old_value == false && _notify == true) + if (old_value == false && _notify == true) notify_change(); return old_value; diff --git a/src/backend/history.hh b/src/backend/history.hh index 28af8ef..41e2665 100644 --- a/src/backend/history.hh +++ b/src/backend/history.hh @@ -45,64 +45,64 @@ namespace sgpem */ class History; - // Forward declarations: - class HistoryObserver; - class Resource; - class Process; - class Thread; - class Request; - class SubRequest; + // Forward declarations: + class HistoryObserver; + class Resource; + class Process; + class Thread; + class Request; + class SubRequest; class SG_DLLEXPORT History { public: - typedef unsigned int size_t; - typedef unsigned int time_t; - typedef unsigned int position; - typedef int prio_t; + typedef unsigned int size_t; + typedef unsigned int time_t; + typedef unsigned int position; + typedef int prio_t; - typedef Environment::resource_key_t resource_key_t; - typedef const std::pair ResourcePair; + typedef Environment::resource_key_t resource_key_t; + typedef const std::pair ResourcePair; History(); - virtual ~History() = 0; - - virtual size_t get_size() const = 0; - virtual const Environment& get_last_environment() const = 0; - virtual const Environment& get_environment_at(position index) const throw(std::out_of_range) = 0; - - virtual void remove(resource_key_t resource_key) = 0; - virtual void remove(Process& process) = 0; - virtual void remove(Thread& thread) = 0; - virtual void remove(Request& request) = 0; - virtual void remove(SubRequest& subrequest) = 0; + virtual ~History() = 0; + + virtual size_t get_size() const = 0; + virtual const Environment& get_last_environment() const = 0; + virtual const Environment& get_environment_at(position index) const throw(std::out_of_range) = 0; + + virtual void remove(resource_key_t resource_key) = 0; + virtual void remove(Process& process) = 0; + virtual void remove(Thread& thread) = 0; + virtual void remove(Request& request) = 0; + virtual void remove(SubRequest& subrequest) = 0; - virtual ResourcePair add_resource(const Glib::ustring& name, - bool preemptable = false, - size_t places = 1, - size_t availability = 0) = 0; + virtual ResourcePair add_resource(const Glib::ustring& name, + bool preemptable = false, + size_t places = 1, + size_t availability = 0) = 0; - virtual Process& add_process(const Glib::ustring& name, - time_t arrival_time, - prio_t base_priority = 0) = 0; + virtual Process& add_process(const Glib::ustring& name, + time_t arrival_time, + prio_t base_priority = 0) = 0; - virtual Thread& add_thread(const Glib::ustring& name, - Process& parent, - time_t cpu_time, - time_t arrival_time = 0, - prio_t base_priority = 0) = 0; + virtual Thread& add_thread(const Glib::ustring& name, + Process& parent, + time_t cpu_time, + time_t arrival_time = 0, + prio_t base_priority = 0) = 0; - virtual Request& add_request(Thread& owner, - time_t instant) = 0; + virtual Request& add_request(Thread& owner, + time_t instant) = 0; - virtual SubRequest& add_subrequest(Request& request, - resource_key_t resource_key, - time_t duration) = 0; + virtual SubRequest& add_subrequest(Request& request, + resource_key_t resource_key, + time_t duration) = 0; - virtual void attach(HistoryObserver& observer); - virtual void detach(const HistoryObserver& observer); + virtual void attach(HistoryObserver& observer); + virtual void detach(const HistoryObserver& observer); /** \brief Enable/disable notifications to registered observers * @@ -113,17 +113,18 @@ namespace sgpem * \return The old value */ virtual bool set_notify_enabled(bool enabled = true); - - protected: - typedef std::vector RegisteredObservers; - RegisteredObservers _observers; - virtual void notify_change(); + protected: + typedef std::vector RegisteredObservers; + RegisteredObservers _observers; + + virtual void notify_change(); private: bool _notify; - }; //~ class History + } + ; //~ class History }//~ namespace sgpem diff --git a/src/backend/history_observer.hh b/src/backend/history_observer.hh index 39aad74..5d21354 100644 --- a/src/backend/history_observer.hh +++ b/src/backend/history_observer.hh @@ -25,16 +25,17 @@ namespace sgpem { - class History; + class History; class HistoryObserver; class SG_DLLEXPORT HistoryObserver { public: - virtual void update(const History& changed_history) = 0; - virtual ~HistoryObserver(); + virtual void update(const History& changed_history) = 0; + virtual ~HistoryObserver(); - }; // class HistoryObserver + } + ; // class HistoryObserver }//~ namespace sgpem diff --git a/src/backend/holt_graph.cc b/src/backend/holt_graph.cc index 6e9b9f3..017f353 100644 --- a/src/backend/holt_graph.cc +++ b/src/backend/holt_graph.cc @@ -27,7 +27,7 @@ using namespace sgpem; using namespace std; -void +void HoltGraph::update(const History& changed_history) { const Environment& env = changed_history.get_last_environment(); @@ -36,33 +36,33 @@ HoltGraph::update(const History& changed_history) _resources.clear(); _active_threads.clear(); _active_requests.clear(); - - for(unsigned int pi = 0; pi < processes.size(); ++pi) + + for (unsigned int pi = 0; pi < processes.size(); ++pi) { vector threads = processes[pi]->get_threads(); - for(unsigned int ti = 0; ti < threads.size(); ++ti) + for (unsigned int ti = 0; ti < threads.size(); ++ti) { vector requests = threads[ti]->get_requests(); - for(unsigned int ri = 0; ri < requests.size(); ++ri) + for (unsigned int ri = 0; ri < requests.size(); ++ri) { - Request& r = *requests[ri]; + Request& r = *requests[ri]; - if(r.get_state() == Request::state_allocated) - { - _active_requests.push_back(&r); - _active_threads.insert(&r.get_thread()); + if (r.get_state() == Request::state_allocated) + { + _active_requests.push_back(&r); + _active_threads.insert(&r.get_thread()); - vector subrequests = r.get_subrequests(); + vector subrequests = r.get_subrequests(); - for(unsigned int sri = 0; sri < subrequests.size(); ++sri) - { - Environment::resource_key_t key = subrequests[sri]->get_resource_key(); + for (unsigned int sri = 0; sri < subrequests.size(); ++sri) + { + Environment::resource_key_t key = subrequests[sri]->get_resource_key(); - _resources.insert(env.get_resources().find(key)->second); - } - } + _resources.insert(env.get_resources().find(key)->second); + } + } } } } diff --git a/src/backend/holt_graph.hh b/src/backend/holt_graph.hh index ce934ec..7422a08 100644 --- a/src/backend/holt_graph.hh +++ b/src/backend/holt_graph.hh @@ -43,9 +43,9 @@ namespace sgpem typedef std::vector Resources; typedef std::vector Threads; typedef std::vector Requests; - + HoltGraph(); - + virtual void update(const History& changed_history); Resources get_resources() const; @@ -56,7 +56,8 @@ namespace sgpem std::set _resources; std::set _active_threads; Requests _active_requests; - }; // class HistoryObserver + } + ; // class HistoryObserver }//~ namespace sgpem diff --git a/src/backend/invalid_plugin_exception.cc b/src/backend/invalid_plugin_exception.cc index 3a87510..fc8bfa1 100644 --- a/src/backend/invalid_plugin_exception.cc +++ b/src/backend/invalid_plugin_exception.cc @@ -25,6 +25,5 @@ using namespace sgpem; InvalidPluginException::InvalidPluginException(const std::string& what) : - std::runtime_error(what) -{ -} + std::runtime_error(what) +{} diff --git a/src/backend/invalid_plugin_exception.hh b/src/backend/invalid_plugin_exception.hh index 64f29d0..bc513be 100644 --- a/src/backend/invalid_plugin_exception.hh +++ b/src/backend/invalid_plugin_exception.hh @@ -31,7 +31,8 @@ namespace sgpem { public: InvalidPluginException(const std::string& what); - }; //~ class InvalidPluginException + } + ; //~ class InvalidPluginException } //~ namespace sgpem diff --git a/src/backend/key_file.cc b/src/backend/key_file.cc index 84a1f3f..db4773b 100644 --- a/src/backend/key_file.cc +++ b/src/backend/key_file.cc @@ -32,22 +32,22 @@ namespace sgpem KeyFile::KeyFile() {} - - + + KeyFile::elements_iterator KeyFile::elements_begin() const { return _elements.begin(); } - - + + KeyFile::elements_iterator KeyFile::elements_end() const { return _elements.end(); } - - + + void KeyFile::insert_key_value(const Glib::ustring& key, const Glib::ustring& value) { @@ -55,62 +55,62 @@ namespace sgpem _elements.insert(val_pair); } - + const Glib::ustring* KeyFile::search_value(const Glib::ustring& key) { const Glib::ustring* ret = 0; elements_iterator cur = _elements.find(key); - if(cur != elements_end()) + if (cur != elements_end()) { ret = &((*cur).second); } return ret; } - + void KeyFile::file_read(const Glib::ustring& filename) { std::ifstream ifs(filename.c_str()); - if(ifs) + if (ifs) { file_read(ifs); } // end - if(ifs) } void - KeyFile::file_read(std::istream& is) + KeyFile::file_read(std::istream& is) { - if(is) + if (is) { _elements.clear(); // erase all elements char buff[KEY_FILE_BUF_LEN]; // - while(is) + while (is) { is.getline(buff, (KEY_FILE_BUF_LEN), '\n'); // if not a comment line... - - if(*buff!='\0' && *buff!='#') + + if (*buff != '\0' && *buff != '#') { char* pos = strchr(buff, '='); - if(pos!=0) + if (pos != 0) { *pos = '\0'; const Glib::ustring key(buff); - const Glib::ustring value(pos+1); + const Glib::ustring value(pos + 1); insert_key_value(key, value); } } // end - if not a comment line... - + } // end - while(ifs)) } // end - if(ifs) } - + void KeyFile::file_write(const Glib::ustring& filename) { std::ofstream ofs(filename.c_str()); - if(ofs) + if (ofs) { file_write(ofs); } // end - if(ofs) @@ -119,10 +119,11 @@ namespace sgpem void KeyFile::file_write(std::ostream& os) { - if(os) + if (os) { elements_iterator iter; - for(iter = elements_begin(); iter != elements_end(); iter++){ + for (iter = elements_begin(); iter != elements_end(); iter++) + { os << (*iter).first << "=" << (*iter).second << std::endl; } } // end - if(ofs) diff --git a/src/backend/key_file.hh b/src/backend/key_file.hh index 99905c8..b2dd6aa 100644 --- a/src/backend/key_file.hh +++ b/src/backend/key_file.hh @@ -31,7 +31,7 @@ namespace sgpem { class KeyFile; - + /** \brief Save and retrieve configuration files formatted as key=value rows. * * This class handles files to store and retrieve configuration preferences @@ -57,7 +57,7 @@ namespace sgpem /** \brief Elements iterator (begin of container) initializer. */ elements_iterator elements_begin() const; - + /** \brief Elements iterator (end of container) initializer */ elements_iterator elements_end() const; @@ -67,7 +67,7 @@ namespace sgpem * \param value The value associated to the key inserted. */ void insert_key_value(const Glib::ustring& key, const Glib::ustring& value); - + /** \brief Insert a new key/value pair. * * \param key The key value to insert. @@ -81,20 +81,20 @@ namespace sgpem * \param filename The file to read from. */ void file_read(const Glib::ustring& filename); - + /** \brief Read a stream into this object. * * \param is the stream to read from. */ void file_read(std::istream& is); - + /** \brief Write into a file from this object. * * \param filename The file to write to. */ void file_write(const Glib::ustring& filename); - + /** \brief Write into a stream from this object. * * \param os the stream to write to. diff --git a/src/backend/module.cc b/src/backend/module.cc index bb53e50..5ae8676 100644 --- a/src/backend/module.cc +++ b/src/backend/module.cc @@ -25,69 +25,69 @@ using namespace sgpem; Module::Module(const Glib::ustring& identifier) throw(InvalidPluginException) : - Glib::Module(identifier), - _enabled(false), - _id(identifier), - on_init_ptr(NULL), - on_exit_ptr(NULL), - describe_ptr(NULL), - get_name_ptr(NULL), - get_author_ptr(NULL), - get_version_ptr(NULL) -{ - if(!*this) throw InvalidPluginException(Module::get_last_error()); + Glib::Module(identifier), + _enabled(false), + _id(identifier), + on_init_ptr(NULL), + on_exit_ptr(NULL), + describe_ptr(NULL), + get_name_ptr(NULL), + get_author_ptr(NULL), + get_version_ptr(NULL) +{ + if (!*this) throw InvalidPluginException(Module::get_last_error()); // Type-safeness here is an optional, as always. :-) std::string prefix = "sgpem__Plugin__"; - if(!(get_symbol(prefix + "on_init", (void*&) on_init_ptr) && - get_symbol(prefix + "on_exit", (void*&) on_exit_ptr) && - get_symbol(prefix + "describe", (void*&) describe_ptr) && - get_symbol(prefix + "get_name", (void*&) get_name_ptr) && - get_symbol(prefix + "get_author", (void*&) get_author_ptr) && - get_symbol(prefix + "get_version", (void*&) get_version_ptr))) + if (!(get_symbol(prefix + "on_init", (void*&) on_init_ptr) && + get_symbol(prefix + "on_exit", (void*&) on_exit_ptr) && + get_symbol(prefix + "describe", (void*&) describe_ptr) && + get_symbol(prefix + "get_name", (void*&) get_name_ptr) && + get_symbol(prefix + "get_author", (void*&) get_author_ptr) && + get_symbol(prefix + "get_version", (void*&) get_version_ptr))) throw InvalidPluginException("incomplete/wrong exported interface"); } - -void + +void Module::set_enabled(bool enabled) { - if(_enabled == enabled) + if (_enabled == enabled) return; - - if(enabled) + + if (enabled) on_init_ptr(); else on_exit_ptr(); - + _enabled = enabled; } -Glib::ustring +Glib::ustring Module::get_name() const { return get_name_ptr(); } -Glib::ustring +Glib::ustring Module::get_author() const { return get_author_ptr(); } -Glib::ustring +Glib::ustring Module::describe() const { return describe_ptr(); } -float +float Module::get_version() const { return get_version_ptr(); } -bool +bool Module::get_enabled() const { return _enabled; diff --git a/src/backend/module.hh b/src/backend/module.hh index 2cef307..7a844c3 100644 --- a/src/backend/module.hh +++ b/src/backend/module.hh @@ -31,29 +31,29 @@ namespace sgpem { class Module; - + class SG_DLLEXPORT Module : public Glib::Module { public: Module(const Glib::ustring& identifier) throw(InvalidPluginException); - + void set_enabled(bool enabled = true); - + Glib::ustring get_name() const; - + Glib::ustring get_author() const; - + Glib::ustring describe() const; - + float get_version() const; - + bool get_enabled() const; private: typedef void (*f_void)(void); typedef Glib::ustring (*f_ustring)(void); typedef float (*f_float)(void); - + bool _enabled; Glib::ustring _id; @@ -63,8 +63,9 @@ namespace sgpem f_ustring get_name_ptr; f_ustring get_author_ptr; f_float get_version_ptr; - - }; //~ class Module + + } + ; //~ class Module } //~ namespace sgpem diff --git a/src/backend/plugin.hh b/src/backend/plugin.hh index 7715f56..5312084 100644 --- a/src/backend/plugin.hh +++ b/src/backend/plugin.hh @@ -46,13 +46,13 @@ extern "C" SG_DLLEXPORT void sgpem__Plugin__on_init(); SG_DLLEXPORT void sgpem__Plugin__on_exit(); - SG_DLLEXPORT const char* sgpem__Plugin__describe(); - SG_DLLEXPORT const char* sgpem__Plugin__get_name(); + SG_DLLEXPORT const char* sgpem__Plugin__describe(); + SG_DLLEXPORT const char* sgpem__Plugin__get_name(); SG_DLLEXPORT const char* sgpem__Plugin__get_author(); - SG_DLLEXPORT float sgpem__Plugin__get_version(); + SG_DLLEXPORT float sgpem__Plugin__get_version(); - // To know why SG_DLLEXPORT must go *before* the return - // value, see http://gcc.gnu.org/ml/gcc-help/2005-04/msg00340.html + // To know why SG_DLLEXPORT must go *before* the return + // value, see http://gcc.gnu.org/ml/gcc-help/2005-04/msg00340.html #ifdef __cplusplus } diff --git a/src/backend/plugin_manager.cc b/src/backend/plugin_manager.cc index 834e877..f9a4d38 100644 --- a/src/backend/plugin_manager.cc +++ b/src/backend/plugin_manager.cc @@ -38,53 +38,53 @@ using namespace std; template class SG_DLLEXPORT Singleton; -std::vector +std::vector PluginManager::get_module_list() const { return _modules; } -void +void PluginManager::rescan_dirs() -{ +{ Module* module = NULL; - for_each(_modules.begin(), _modules.end(), - memory::deletor()); + for_each(_modules.begin(), _modules.end(), + memory::deletor()); _modules.clear(); - + GlobalPreferences& prefs = GlobalPreferences::get_instance(); GlobalPreferences::dir_iterator it = prefs.modules_dir_begin(); - + Glib::PatternSpec shared_obj(Glib::ustring("*.") + G_MODULE_SUFFIX); - - while(it != prefs.modules_dir_end()) + + while (it != prefs.modules_dir_end()) { Glib::Dir dir(*it); - for(Glib::DirIterator dir_it = dir.begin(); dir_it != dir.end(); ++dir_it) + for (Glib::DirIterator dir_it = dir.begin(); dir_it != dir.end(); ++dir_it) { // only attempt to load .so files - if(shared_obj.match(*dir_it)) + if (shared_obj.match(*dir_it)) { - std::string module_path = Module::build_path(*it, *dir_it); + std::string module_path = Module::build_path(*it, *dir_it); - std::cerr << "Attempting to load module at path " << module_path << std::endl; - - try - { - module = new Module(module_path); + std::cerr << "Attempting to load module at path " << module_path << std::endl; + + try + { + module = new Module(module_path); _modules.push_back(module); - std::cerr << "\tSuccess" << std::endl; - } - catch(InvalidPluginException e) - { - std::cerr << "\tFailed, invalid plugin: " << e.what() << std::endl; - } + std::cerr << "\tSuccess" << std::endl; + } + catch (InvalidPluginException e) + { + std::cerr << "\tFailed, invalid plugin: " << e.what() << std::endl; + } } } - + it++; } } diff --git a/src/backend/plugin_manager.hh b/src/backend/plugin_manager.hh index ac622a9..5011f00 100644 --- a/src/backend/plugin_manager.hh +++ b/src/backend/plugin_manager.hh @@ -35,7 +35,7 @@ namespace sgpem namespace sgpem { class PluginManager; - + class SG_DLLEXPORT PluginManager : public Singleton { friend class Singleton; @@ -47,9 +47,10 @@ namespace sgpem private: PluginManager(); - std::vector _modules; + std::vector _modules; - }; //~ class PluginManager + } + ; //~ class PluginManager } //~ namespace sgpem diff --git a/src/backend/policy_parameters.cc b/src/backend/policy_parameters.cc index 7fcb695..0c9ea1c 100644 --- a/src/backend/policy_parameters.cc +++ b/src/backend/policy_parameters.cc @@ -113,7 +113,7 @@ PolicyParameters::get_registered_string_parameters() const /** Tries to set the value to the parameter named "name". - \returns TRUE if the parameter named "name" has been previously registered and the value + \returns TRUE if the parameter named "name" has been previously registered and the value stays in the range permitted by the parameter. \returns FALSE in the other cases. */ @@ -135,7 +135,7 @@ PolicyParameters::set_int(ustring name, const int& value) /** Tries to set the value to the parameter named "name". - \returns TRUE if the parameter named "name" has been previously registered and the value + \returns TRUE if the parameter named "name" has been previously registered and the value stays in the range permitted by the parameter. \returns FALSE in the other cases. */ diff --git a/src/backend/ready_queue.cc b/src/backend/ready_queue.cc index 46d515b..de52d77 100644 --- a/src/backend/ready_queue.cc +++ b/src/backend/ready_queue.cc @@ -27,48 +27,48 @@ using sgpem::ReadyQueue; void ReadyQueue::swap(position a, position b) - throw (std::out_of_range) +throw (std::out_of_range) { - if(a == b) return; - - // Usage of "at()" isn't casual: - // at() checks indexes, "[]" doesn't. - // Once we've done the check once, we - // can assume it's safe to use "[]"; - // this for performance reasons. - Thread* temp = _scheds.at(a); - _scheds[a] = _scheds.at(b); - _scheds[b] = temp; + if (a == b) return; + + // Usage of "at()" isn't casual: + // at() checks indexes, "[]" doesn't. + // Once we've done the check once, we + // can assume it's safe to use "[]"; + // this for performance reasons. + Thread* temp = _scheds.at(a); + _scheds[a] = _scheds.at(b); + _scheds[b] = temp; } ReadyQueue::size_t ReadyQueue::size() const { - return _scheds.size(); + return _scheds.size(); } sgpem::Thread& ReadyQueue::get_item_at(position index) - throw (std::out_of_range) +throw (std::out_of_range) { - // Checks index access - return *_scheds.at(index); + // Checks index access + return *_scheds.at(index); } const sgpem::Thread& ReadyQueue::get_item_at(position index) const - throw (std::out_of_range) +throw (std::out_of_range) { - // Checks index access - return *_scheds.at(index); + // Checks index access + return *_scheds.at(index); } void ReadyQueue::append(Thread& thread) { - _scheds.push_back(&thread); + _scheds.push_back(&thread); } void diff --git a/src/backend/ready_queue.hh b/src/backend/ready_queue.hh index b232a79..6c7434f 100644 --- a/src/backend/ready_queue.hh +++ b/src/backend/ready_queue.hh @@ -28,25 +28,25 @@ namespace sgpem { - class ReadyQueue; - class Thread; + class ReadyQueue; + class Thread; class SG_DLLEXPORT ReadyQueue { public: - typedef unsigned int position; - typedef unsigned int size_t; + typedef unsigned int position; + typedef unsigned int size_t; - void swap(position a, position b) throw (std::out_of_range); - size_t size() const; - Thread& get_item_at(position index) throw (std::out_of_range); - const Thread& get_item_at(position index) const throw (std::out_of_range); - void append(Thread& schedulable); + void swap(position a, position b) throw (std::out_of_range); + size_t size() const; + Thread& get_item_at(position index) throw (std::out_of_range); + const Thread& get_item_at(position index) const throw (std::out_of_range); + void append(Thread& schedulable); void erase_first(); - + private: - typedef std::vector Threads; - Threads _scheds; + typedef std::vector Threads; + Threads _scheds; }; } diff --git a/src/backend/request.hh b/src/backend/request.hh index 6f779c5..3dc3708 100644 --- a/src/backend/request.hh +++ b/src/backend/request.hh @@ -40,13 +40,13 @@ namespace sgpem state_allocated = 1 << 1, state_future = 1 << 2, state_exhausted = 1 << 3, - state_allocable = 1 << 4 + state_allocable = 1 << 4 }; virtual ~Request(); - + virtual Thread& get_thread() = 0; - + virtual bool operator==(const Request& op2) const = 0; virtual std::vector get_subrequests() = 0; diff --git a/src/backend/resource.hh b/src/backend/resource.hh index bfe0fe7..88cb704 100644 --- a/src/backend/resource.hh +++ b/src/backend/resource.hh @@ -34,7 +34,7 @@ namespace sgpem public: virtual ~Resource(); - virtual bool operator==(const Resource& op2) const = 0; + virtual bool operator==(const Resource& op2) const = 0; virtual Glib::ustring get_name() const = 0; virtual unsigned int get_places() const = 0; diff --git a/src/backend/resource_policies_gatekeeper.cc b/src/backend/resource_policies_gatekeeper.cc index c619bef..979ed3d 100644 --- a/src/backend/resource_policies_gatekeeper.cc +++ b/src/backend/resource_policies_gatekeeper.cc @@ -55,7 +55,7 @@ ResourcePoliciesGatekeeper::register_manager(ResourcePolicyManager* manager) ManagerIterator end = _registered.end(); - if(find(_registered.begin(), end, manager) == end) + if (find(_registered.begin(), end, manager) == end) _registered.push_back(manager); } @@ -67,7 +67,7 @@ ResourcePoliciesGatekeeper::unregister_manager(ResourcePolicyManager* manager) ManagerIterator end = _registered.end(); ManagerIterator pos = find(_registered.begin(), end, manager); - if(pos != end) + if (pos != end) { deactivate_policies(**pos); _registered.erase(pos); @@ -81,7 +81,7 @@ ResourcePoliciesGatekeeper::get_current_policy(History* history) throw(runtime_e PolicyIterator policy = _active_policies.find(history); - if(policy == _active_policies.end()) + if (policy == _active_policies.end()) throw runtime_error("No active policy associated with this " "history is available."); @@ -97,8 +97,7 @@ ResourcePoliciesGatekeeper::activate_policy(History *history, ResourcePolicy* po } ResourcePoliciesGatekeeper::ResourcePoliciesGatekeeper() -{ -} +{} void ResourcePoliciesGatekeeper::deactivate_policies(const ResourcePolicyManager& manager) @@ -107,18 +106,19 @@ ResourcePoliciesGatekeeper::deactivate_policies(const ResourcePolicyManager& man const vector& policies = manager.get_avail_policies(); - for(AvailableIt avail_it = policies.begin(); avail_it != policies.end(); ++avail_it) + for (AvailableIt avail_it = policies.begin(); avail_it != policies.end(); ++avail_it) { // TODO isn't there a way to write more compact code by using // library utilities? - for(PolicyIterator it = _active_policies.begin(); it != _active_policies.end();) + for (PolicyIterator it = _active_policies.begin(); it != _active_policies.end();) { - // FIXME Is this necessary? It just came across my mind the idea that + // FIXME Is this necessary? It just came across my mind the idea that // incrementing an invalid iterator might be unsafe... - PolicyIterator next = it; ++next; - - if(it->second == *avail_it) - _active_policies.erase(it); + PolicyIterator next = it; + ++next; + + if (it->second == *avail_it) + _active_policies.erase(it); it = next; } diff --git a/src/backend/resource_policies_gatekeeper.hh b/src/backend/resource_policies_gatekeeper.hh index efce57a..e70bc4d 100644 --- a/src/backend/resource_policies_gatekeeper.hh +++ b/src/backend/resource_policies_gatekeeper.hh @@ -51,26 +51,26 @@ namespace sgpem public: typedef std::vector Managers; - + const Managers& get_registered() const; - void register_manager(ResourcePolicyManager* manager); + void register_manager(ResourcePolicyManager* manager); - void unregister_manager(ResourcePolicyManager* manager); + void unregister_manager(ResourcePolicyManager* manager); ResourcePolicy& get_current_policy(History* history) throw(std::runtime_error); - void activate_policy(History* history, ResourcePolicy* policy); + void activate_policy(History* history, ResourcePolicy* policy); private: ResourcePoliciesGatekeeper(); //private constructor. ResourcePoliciesGatekeeper(const ResourcePoliciesGatekeeper&); ResourcePoliciesGatekeeper& operator=(const ResourcePoliciesGatekeeper&); - + void deactivate_policies(const ResourcePolicyManager& manager); std::vector _registered; - std::map _active_policies; + std::map _active_policies; }; }//~ namespace sgpem diff --git a/src/backend/resource_policy.hh b/src/backend/resource_policy.hh index d0c8d1c..ebc7864 100644 --- a/src/backend/resource_policy.hh +++ b/src/backend/resource_policy.hh @@ -56,8 +56,8 @@ namespace sgpem Because it's a pure virtual method, must be re-implemented in concrete derived classes. */ - virtual void enforce() throw(UserInterruptException) = 0; - + virtual void enforce() throw(UserInterruptException) = 0; + /** Gets a string description of the policy. diff --git a/src/backend/schedulable.hh b/src/backend/schedulable.hh index 8406389..1dd979d 100644 --- a/src/backend/schedulable.hh +++ b/src/backend/schedulable.hh @@ -51,7 +51,7 @@ namespace sgpem virtual ~Schedulable() = 0; - virtual bool operator==(const Schedulable& op2) const = 0; + virtual bool operator==(const Schedulable& op2) const = 0; virtual Glib::ustring get_name() const = 0; diff --git a/src/backend/scheduler.cc b/src/backend/scheduler.cc index 070510d..483f09a 100644 --- a/src/backend/scheduler.cc +++ b/src/backend/scheduler.cc @@ -50,23 +50,23 @@ typedef std::vector Threads; class Extender { - public: +public: enum walk_purpose { walk_to_sweep = 0, - walk_to_advance = 1, + walk_to_advance = 1, walk_to_update = 2, walk_to_allocate_cpu = 3, walk_to_allocate_resources = 4 }; - Extender(auto_ptr & _env, walk_purpose _walk, unsigned int _front) - : env(_env), walk(_walk), front(_front) - {} + Extender(auto_ptr & _env, walk_purpose _walk, unsigned int _front) + : env(_env), walk(_walk), front(_front) + {} /// \brief Manages a single SubRequest object, depending on its state. - /// Zero step: any -> terminated. Added to cope with malformed threads. + /// Zero step: any -> terminated. Added to cope with malformed threads. /// First step: allocated -> terminated. /// Second step: non-allocable -> allocable. /// Third step: allocable -> allocated, or future -> allocated. @@ -78,13 +78,40 @@ class Extender /// the queue position. Anyway, this factoring may lead to code dispersion. /// I think it is better to hold the computational core in one single place. void - extendSubRequest(DynamicSubRequest* sp) + extendSubRequest(DynamicSubRequest* sp) { - DynamicSubRequest& s = *sp; + DynamicSubRequest& s = *sp; switch (walk) { - /// Terminates directly the subrequest + /// Terminates directly the subrequest case walk_to_sweep: + { + s.set_state(Request::state_exhausted); + /// Remove the subrequest (pointer) from the queue. + bool found = false; + typedef Environment::SubRequestQueue SubRequestQueue; + SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); + SubRequestQueue::iterator it = queue.begin(); + for (; !found && it != queue.end(); it++) + if ((*it) == sp) + { + found = true; + queue.erase(it); + } + break; + } + /// Updates the state of an ALLOCATED subrequest, decreasing appropriate + /// counters, and checks if it become TERMINATED. In the latter case the + /// function finds the position of the subrequest (pointer) in the + /// requested resource's queue and removes it. + case walk_to_advance: + { + if (s.get_state() != Request::state_allocated) + break; + /// Decrease remaining time, since the resource has been used. + s.decrease_remaining_time(); + /// Check for termination. + if (s.get_remaining_time() == 0) { s.set_state(Request::state_exhausted); /// Remove the subrequest (pointer) from the queue. @@ -93,75 +120,48 @@ class Extender SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); SubRequestQueue::iterator it = queue.begin(); for (; !found && it != queue.end(); it++) - if ((*it) == sp) + { + if ((*it) == &s) { found = true; queue.erase(it); } - break; - } - /// Updates the state of an ALLOCATED subrequest, decreasing appropriate - /// counters, and checks if it become TERMINATED. In the latter case the - /// function finds the position of the subrequest (pointer) in the - /// requested resource's queue and removes it. - case walk_to_advance: - { - if (s.get_state() != Request::state_allocated) - break; - /// Decrease remaining time, since the resource has been used. - s.decrease_remaining_time(); - /// Check for termination. - if (s.get_remaining_time() == 0) - { - s.set_state(Request::state_exhausted); - /// Remove the subrequest (pointer) from the queue. - bool found = false; - typedef Environment::SubRequestQueue SubRequestQueue; - SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); - SubRequestQueue::iterator it = queue.begin(); - for (; !found && it != queue.end(); it++) - { - if ((*it) == &s) - { - found = true; - queue.erase(it); - } - } } - break; } + break; + } /// Updates the state of a non-ALLOCATED subrequest, in case it become /// ALLOCABLE or UNALLOCABLE, which may happen only when a resource has - /// been released. + /// been released. /// We could jump this check if no resource were released. /// It finds the position of the subrequest (pointer) in the requested /// resource's queue. If the position is within the places of the /// resource, the subrequest is ALLOCABLE. - /// + /// case walk_to_update: - { - if (s.get_state() != Request::state_unallocable - && s.get_state() != Request::state_allocable) - break; - /// The subrequest is in the queue for sure. Let's find it! - /// I really need an integer for this operation. - uint position = 0; - Environment::SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); - Environment::SubRequestQueue::iterator it = queue.begin(); - while (it != queue.end()) - { - if (*it == &s) - break; - it++; - position++; - } - /// Watch out: in a resource with 2 places, 0 and 1 are valid queue - /// positions, 2 is right one place out. - s.set_state(position >= env->get_resources().find(s.get_resource_key())->second->get_places() ? - Request::state_unallocable : Request::state_allocable); + { + if (s.get_state() != Request::state_unallocable + && s.get_state() != Request::state_allocable) break; + /// The subrequest is in the queue for sure. Let's find it! + /// I really need an integer for this operation. + uint position = 0; + Environment::SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); + Environment::SubRequestQueue::iterator it = queue.begin(); + while (it != queue.end()) + { + if (*it == &s) + break; + it++; + position++; } + /// Watch out: in a resource with 2 places, 0 and 1 are valid queue + /// positions, 2 is right one place out. + s.set_state(position >= env->get_resources().find(s.get_resource_key())->second->get_places() ? + Request::state_unallocable : Request::state_allocable); + break; + } /// Updates the state of a FUTURE subrequest when the time has come /// for it to be raised, setting it as allocable it if it is the case, @@ -171,30 +171,30 @@ class Extender /// If the position is within the places of the resource, the subrequest /// is ALLOCABLE, otherwise it is NON-ALLOCABLE. case walk_to_allocate_cpu: - { - if (s.get_state() != Request::state_future) - break; - Environment::SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); - /// Enqueue the subrequest at the back of the queue. - queue.push_back(&s); - - /// TODO: right here, right now we should call the resource policy to - /// update the queue. Updates the state of the subrequest depending - /// on the position in the queue, as explained before. - s.set_state(queue.size() > env->get_resources().find(s.get_resource_key())->second->get_places() ? - Request::state_unallocable : Request::state_allocable); - // Oh I miss ML so much. + { + if (s.get_state() != Request::state_future) break; - } + Environment::SubRequestQueue& queue = env->get_request_queue(s.get_resource_key()); + /// Enqueue the subrequest at the back of the queue. + queue.push_back(&s); + + /// TODO: right here, right now we should call the resource policy to + /// update the queue. Updates the state of the subrequest depending + /// on the position in the queue, as explained before. + s.set_state(queue.size() > env->get_resources().find(s.get_resource_key())->second->get_places() ? + Request::state_unallocable : Request::state_allocable); + // Oh I miss ML so much. + break; + } /// This is ugly, but hey, none's perfect. /// Updates the state of a ALLOCABLE subrequest allocating it. case walk_to_allocate_resources: - { - if (s.get_state() == Request::state_allocable) - s.set_state(Request::state_allocated); - break; - } + { + if (s.get_state() == Request::state_allocable) + s.set_state(Request::state_allocated); + break; + } } } @@ -206,7 +206,7 @@ class Extender /// updating the contained subrequests. The state of the request is then /// a function of the states of the subrequests. /// - /// Zero step: any -> terminated. Added to cope with malformed threads. + /// Zero step: any -> terminated. Added to cope with malformed threads. /// First step: allocated -> terminated. /// Second step: non-allocable -> allocable. /// Third step: allocable -> allocated, or future -> allocated. @@ -221,195 +221,195 @@ class Extender switch (walk) { case walk_to_sweep: - { - typedef vector SubRequests; - SubRequests list = r.get_dynamic_subrequests(); - for (SubRequests::iterator it = list.begin(); it != list.end(); it++) - extendSubRequest(*it); - break; - } + { + typedef vector SubRequests; + SubRequests list = r.get_dynamic_subrequests(); + for (SubRequests::iterator it = list.begin(); it != list.end(); it++) + extendSubRequest(*it); + break; + } /// Updates the state of an ALLOCATED request. case walk_to_advance: - { - if (r.get_state() != Request::state_allocated) - break; - typedef vector SubRequests; - SubRequests list = r.get_dynamic_subrequests(); - for (SubRequests::iterator it = list.begin(); it != list.end(); it++) - extendSubRequest(*it); + { + if (r.get_state() != Request::state_allocated) break; - } + typedef vector SubRequests; + SubRequests list = r.get_dynamic_subrequests(); + for (SubRequests::iterator it = list.begin(); it != list.end(); it++) + extendSubRequest(*it); + break; + } /// Updates the state of a NON-ALLOCABLE request. case walk_to_update: - { - if (r.get_state() != Request::state_unallocable) - break; - typedef vector SubRequests; - SubRequests list = r.get_dynamic_subrequests(); - for (SubRequests::iterator it = list.begin(); it != list.end(); it++) - extendSubRequest(*it); + { + if (r.get_state() != Request::state_unallocable) break; - } + typedef vector SubRequests; + SubRequests list = r.get_dynamic_subrequests(); + for (SubRequests::iterator it = list.begin(); it != list.end(); it++) + extendSubRequest(*it); + break; + } /// Updates the state of an ALLOCABLE or FUTURE request. case walk_to_allocate_cpu: - { - /// This is the only interesting case. If the current instant, measured - /// over the containing process execution time, is equal to the instant - /// in which the request has to be raised, the subrequests are - /// recursively updated for the first time ever, and their status - /// changes from FUTURE to something else. - if (r.get_state() == Request::state_future + { + /// This is the only interesting case. If the current instant, measured + /// over the containing process execution time, is equal to the instant + /// in which the request has to be raised, the subrequests are + /// recursively updated for the first time ever, and their status + /// changes from FUTURE to something else. + if (r.get_state() == Request::state_future && r.get_instant() == front) - { - typedef vector SubRequests; - SubRequests list = r.get_dynamic_subrequests(); - for (SubRequests::iterator it = list.begin(); it != list.end(); it++) - extendSubRequest(*it); - } - /// Finally, allocates the reuqest if possible. - if (r.get_state() == Request::state_allocable) - { - typedef vector SubRequests; - SubRequests list = r.get_dynamic_subrequests(); - walk = walk_to_allocate_resources; - for (SubRequests::iterator it = list.begin(); it != list.end(); it++) - extendSubRequest(*it); - walk = walk_to_allocate_cpu; - } - break; + { + typedef vector SubRequests; + SubRequests list = r.get_dynamic_subrequests(); + for (SubRequests::iterator it = list.begin(); it != list.end(); it++) + extendSubRequest(*it); } + /// Finally, allocates the reuqest if possible. + if (r.get_state() == Request::state_allocable) + { + typedef vector SubRequests; + SubRequests list = r.get_dynamic_subrequests(); + walk = walk_to_allocate_resources; + for (SubRequests::iterator it = list.begin(); it != list.end(); it++) + extendSubRequest(*it); + walk = walk_to_allocate_cpu; + } + break; + } } } -/* + /* - // the following methods are never used in step forward (by now) + // the following methods are never used in step forward (by now) - /// \brief Manages a single Thread object, depending on its state. - /// - /// First step: running -> terminated, or running -> running, or - /// running -> ready. - /// Second step: future -> ready or blocked -> ready. - /// Third step: ready -> running, or ready -> blocked - /// - /// The front is shifted to reflect the thread time: this is useful - /// for reasons analogous to those found in extendProcess. - void - extendThread(DynamicThread& t) - { - /// Shifts the front. The old front will be restored on exit. - int old_front = front; - front = t.get_elapsed_time(); - switch (walk) + /// \brief Manages a single Thread object, depending on its state. + /// + /// First step: running -> terminated, or running -> running, or + /// running -> ready. + /// Second step: future -> ready or blocked -> ready. + /// Third step: ready -> running, or ready -> blocked + /// + /// The front is shifted to reflect the thread time: this is useful + /// for reasons analogous to those found in extendProcess. + void + extendThread(DynamicThread& t) { + /// Shifts the front. The old front will be restored on exit. + int old_front = front; + front = t.get_elapsed_time(); + switch (walk) + { - /// If the thread is RUNNING, its requests are updated in cascade, - /// the counters are decreased, and the state is updated depending - /// on the remaining time and the remaining quantum. - case walk_to_advance: - { - if (t.state != "RUNNING") - break; - /// Update the requests. - for (int j = 0; j < t.requests.size(); j++) - t.requests[j].accept(*this); - t.decrease_remaining_time(); - /// If the quantum is finished, we may need to change the state - /// of the thread to ready. - if (t.get_remaining_cpu_time() != 0 && t.remaining_quantum == 0 - && !priority_preemptable && quantum_preemptable) + /// If the thread is RUNNING, its requests are updated in cascade, + /// the counters are decreased, and the state is updated depending + /// on the remaining time and the remaining quantum. + case walk_to_advance: { - t.state = "READY"; - env->readyqueue.erase(env->readyqueue.begin()); - env->readyqueue.push_back(&t); - /// FIXME: we should call the policy, with event "arrival"; - /// this works for round robin only. - } - /// If the remaining is finished, the thread is terminated. - if (t.get_remaining_cpu_time() == 0) - { - t.state = "TERMINATED"; - env->readyqueue.erase(env->readyqueue.begin()); - } - break; - } - /// If the thread is FUTURE, checks if it's time to arrive. - /// If the thread is BLOCKED, checks if requests have changed - /// their status since the last time, and if none of them is - /// BLOCKED, the thread state is set to READY. - case walk_to_update: - { - /// Remember, front has been localized to current thread time. - if (t.state == "FUTURE" && t.arrival == old_front) - { - t.state = "READY"; - env->readyqueue.push_back(&t); - /// FIXME: we should call the policy, with event "new arrival". - } - if (t.state == "BLOCKED") - { - bool blocked = false; - for (int j = 0; j < t.requests.size() && !blocked; j++) - { + if (t.state != "RUNNING") + break; + /// Update the requests. + for (int j = 0; j < t.requests.size(); j++) t.requests[j].accept(*this); - if (t.requests[j].get_state() == "NON-ALLOCABLE") - blocked = true; + t.decrease_remaining_time(); + /// If the quantum is finished, we may need to change the state + /// of the thread to ready. + if (t.get_remaining_cpu_time() != 0 && t.remaining_quantum == 0 + && !priority_preemptable && quantum_preemptable) + { + t.state = "READY"; + env->readyqueue.erase(env->readyqueue.begin()); + env->readyqueue.push_back(&t); + /// FIXME: we should call the policy, with event "arrival"; + /// this works for round robin only. } - if (!blocked) + /// If the remaining is finished, the thread is terminated. + if (t.get_remaining_cpu_time() == 0) + { + t.state = "TERMINATED"; + env->readyqueue.erase(env->readyqueue.begin()); + } + break; + } + /// If the thread is FUTURE, checks if it's time to arrive. + /// If the thread is BLOCKED, checks if requests have changed + /// their status since the last time, and if none of them is + /// BLOCKED, the thread state is set to READY. + case walk_to_update: + { + /// Remember, front has been localized to current thread time. + if (t.state == "FUTURE" && t.arrival == old_front) { t.state = "READY"; env->readyqueue.push_back(&t); - /// FIXME: we should call the policy, with event "arrival". + /// FIXME: we should call the policy, with event "new arrival". } - } - break; - } - - /// If the thread is the first on the ready_queue, try to run. The - /// thread may block on a request. - case walk_to_allocate_cpu: - { - ReadyQueue & queue = env->get_sorted_queue(); - /// Check if we are eligible to run. - if (queue.size() != 0 && &t == &queue.get_item_at(0)) - { - /// Lets' try to run! - t.set_state(Schedulable::state_running); - - typedef vector Requests; - Requests list = t.get_dynamic_requests(); - for (Requests::iterator it = list.begin(); it != list.end() - && t.get_state() != Schedulable::state_blocked; it++) - { - extendRequest(**it); - /// If one request is not allocable, the thread can't run. - if ((**it).get_state() == Request::state_unallocable) + if (t.state == "BLOCKED") + { + bool blocked = false; + for (int j = 0; j < t.requests.size() && !blocked; j++) { - t.set_state(Schedulable::state_blocked); - queue.erase_first(); + t.requests[j].accept(*this); + if (t.requests[j].get_state() == "NON-ALLOCABLE") + blocked = true; } - } - -// /// If the thread is runnable, we may need to refill its quantum. -// if (t.state == "RUNNING" && t.remaining_quantum == 0) -// t.remaining_quantum = quantum_size; + if (!blocked) + { + t.state = "READY"; + env->readyqueue.push_back(&t); + /// FIXME: we should call the policy, with event "arrival". + } + } + break; } - break; - } + /// If the thread is the first on the ready_queue, try to run. The + /// thread may block on a request. + case walk_to_allocate_cpu: + { + ReadyQueue & queue = env->get_sorted_queue(); + /// Check if we are eligible to run. + if (queue.size() != 0 && &t == &queue.get_item_at(0)) + { + /// Lets' try to run! + t.set_state(Schedulable::state_running); + + typedef vector Requests; + Requests list = t.get_dynamic_requests(); + for (Requests::iterator it = list.begin(); it != list.end() + && t.get_state() != Schedulable::state_blocked; it++) + { + extendRequest(**it); + /// If one request is not allocable, the thread can't run. + if ((**it).get_state() == Request::state_unallocable) + { + t.set_state(Schedulable::state_blocked); + queue.erase_first(); + } + } + + // /// If the thread is runnable, we may need to refill its quantum. + // if (t.state == "RUNNING" && t.remaining_quantum == 0) + // t.remaining_quantum = quantum_size; + } + break; + } + + } + front = old_front; } - front = old_front; - } -*/ + */ // private class members - private: +private: - auto_ptr & env; - int walk; - unsigned int front; + auto_ptr & env; + int walk; + unsigned int front; }; @@ -432,32 +432,32 @@ class Extender // Collects all threads of an environment into a single vector -static void -collect_threads(const std::vector& procs, - std::vector& collected_threads) +static void +collect_threads(const std::vector& procs, + std::vector& collected_threads) { typedef std::vector Processes; typedef std::vector Threads; collected_threads.clear(); - for(Processes::const_iterator it1 = procs.begin(); it1 != procs.end(); it1++) - { - const Threads& ts = ((DynamicProcess&) **it1).get_dynamic_threads(); - collected_threads.insert(collected_threads.end(), ts.begin(), ts.end()); - } + for (Processes::const_iterator it1 = procs.begin(); it1 != procs.end(); it1++) + { + const Threads& ts = ((DynamicProcess&) **it1).get_dynamic_threads(); + collected_threads.insert(collected_threads.end(), ts.begin(), ts.end()); + } } -static void prepare_ready_queue(ConcreteEnvironment& snapshot, - std::vector& all_threads) +static void prepare_ready_queue(ConcreteEnvironment& snapshot, + std::vector& all_threads) { - typedef std::vector Threads; - ReadyQueue& queue = snapshot.get_sorted_queue(); - assert(queue.size() == 0); + typedef std::vector Threads; + ReadyQueue& queue = snapshot.get_sorted_queue(); + assert(queue.size() == 0); - for(Threads::const_iterator it = all_threads.begin(); - it != all_threads.end(); it++) - if((*it)->get_state() == Schedulable::state_ready) - queue.append(**it); + for (Threads::const_iterator it = all_threads.begin(); + it != all_threads.end(); it++) + if ((*it)->get_state() == Schedulable::state_ready) + queue.append(**it); } // --------------------------------------------------------- @@ -467,9 +467,8 @@ static void prepare_ready_queue(ConcreteEnvironment& snapshot, //private constructor. The parameter is discarded Scheduler::Scheduler() - : _ready_queue(NULL), _policy(NULL), _step_mutex() -{ -} + : _ready_queue(NULL), _policy(NULL), _step_mutex() +{} ReadyQueue* @@ -493,159 +492,159 @@ Scheduler::reset_status() CPUPolicy* Scheduler::get_policy() { - return _policy; + return _policy; } bool Scheduler::step_forward(History& history, CPUPolicy& cpu_policy) throw(UserInterruptException) { - // This very method should be exclusive: no concurrent behaviour, from when we - // store a readyqueue and policy pointer for the user-policy to retrieve, to when - // the policy returns - // TODO: restrict this area to maximise parallelism - Glib::Mutex::Lock lock(_step_mutex); + // This very method should be exclusive: no concurrent behaviour, from when we + // store a readyqueue and policy pointer for the user-policy to retrieve, to when + // the policy returns + // TODO: restrict this area to maximise parallelism + Glib::Mutex::Lock lock (_step_mutex); - // NOTE: Be sure to read the *ORIGINAL* documentation in the design document for this method! + // NOTE: Be sure to read the *ORIGINAL* documentation in the design document for this method! - // FIXME: handle me! I'm not just a pretty boolean, I want to be *USED*! *EXPLOITED*! - // *RAPED*! *MAKE ME BLEED*! - bool simulation_ended = true; // Assume we've finished. Then prove me wrong. - // since history always contains at leas one element.. - assert (history.get_size() > 0); - unsigned int current_instant = history.get_size() - 1; /* They should be equivalent */ + // FIXME: handle me! I'm not just a pretty boolean, I want to be *USED*! *EXPLOITED*! + // *RAPED*! *MAKE ME BLEED*! + bool simulation_ended = true; // Assume we've finished. Then prove me wrong. + // since history always contains at leas one element.. + assert (history.get_size() > 0); + unsigned int current_instant = history.get_size() - 1; /* They should be equivalent */ - ConcreteHistory& concrete_history = (ConcreteHistory&) history; - - // Use an auto_ptr since we've some exceptions in the coming... - auto_ptr new_snapshot(new ConcreteEnvironment(concrete_history.get_last_environment())); - - Threads all_threads; - DynamicThread* running_thread = NULL; + ConcreteHistory& concrete_history = (ConcreteHistory&) history; - collect_threads(new_snapshot->get_processes(), all_threads); + // Use an auto_ptr since we've some exceptions in the coming... + auto_ptr new_snapshot(new ConcreteEnvironment(concrete_history.get_last_environment())); - // designer + implementer (Matteo) comment follows: + Threads all_threads; + DynamicThread* running_thread = NULL; - for(Threads::iterator it = all_threads.begin(); it != all_threads.end(); it++) - { - DynamicThread& current = **it; - - // 1. mark future threads as ready, if appropriate - if(current.get_state() == Schedulable::state_future) - { - // if there is at least a future process, don't terminate the simulation - Process& parent = current.get_process(); - if (parent.get_state() == Schedulable::state_future) - simulation_ended = false; - // start a thread only if its parent is arrived! - if(parent.get_arrival_time() <= current_instant && parent.get_elapsed_time() == current.get_arrival_time()) - { - current.set_state(Schedulable::state_ready); - // in this way we will never have threads ready having remaining time == 0 - if (current.get_elapsed_time() == current.get_total_cpu_time()) - current.set_state(Schedulable::state_terminated); - } - } + collect_threads(new_snapshot->get_processes(), all_threads); - // Save the current running thread for future usage, if it hasn't ended - // its allotted time - if(current.get_state() == Schedulable::state_running) - { - assert(running_thread == NULL); // ... and one to bind them all. - running_thread = ¤t; // Even if we change its state to terminate + // designer + implementer (Matteo) comment follows: - // increasing the time elapsed of the running thread + process - // should be done here as the first thing, instead than - // directly after selecting them - if(current.get_total_cpu_time() - current.get_elapsed_time() > 0) - current.decrease_remaining_time(); - - // 2. mark threads that used all their allotted time as terminated - if(current.get_total_cpu_time() - current.get_elapsed_time() == 0) - current.set_state(Schedulable::state_terminated); - } - - // 3. check for simulation termination (we can directly use threads - // for this check, since processes' state is based upon threads' one) - if( /* we still think that */ simulation_ended && - (current.get_state() & (Schedulable::state_blocked | - Schedulable::state_terminated)) == 0) - simulation_ended = false; - } - - // 4a. Look for exhausted requests for the running thread - if(running_thread != NULL) + for (Threads::iterator it = all_threads.begin(); it != all_threads.end(); it++) { - bool running_terminated = running_thread->get_state() == Schedulable::state_terminated; - Extender e(new_snapshot, - running_terminated ? Extender::walk_to_sweep : Extender::walk_to_advance, - running_thread->get_elapsed_time()); + DynamicThread& current = **it; + + // 1. mark future threads as ready, if appropriate + if (current.get_state() == Schedulable::state_future) + { + // if there is at least a future process, don't terminate the simulation + Process& parent = current.get_process(); + if (parent.get_state() == Schedulable::state_future) + simulation_ended = false; + // start a thread only if its parent is arrived! + if (parent.get_arrival_time() <= current_instant && parent.get_elapsed_time() == current.get_arrival_time()) + { + current.set_state(Schedulable::state_ready); + // in this way we will never have threads ready having remaining time == 0 + if (current.get_elapsed_time() == current.get_total_cpu_time()) + current.set_state(Schedulable::state_terminated); + } + } + + // Save the current running thread for future usage, if it hasn't ended + // its allotted time + if (current.get_state() == Schedulable::state_running) + { + assert(running_thread == NULL); // ... and one to bind them all. + running_thread = ¤t; // Even if we change its state to terminate + + // increasing the time elapsed of the running thread + process + // should be done here as the first thing, instead than + // directly after selecting them + if (current.get_total_cpu_time() - current.get_elapsed_time() > 0) + current.decrease_remaining_time(); + + // 2. mark threads that used all their allotted time as terminated + if (current.get_total_cpu_time() - current.get_elapsed_time() == 0) + current.set_state(Schedulable::state_terminated); + } + + // 3. check for simulation termination (we can directly use threads + // for this check, since processes' state is based upon threads' one) + if ( /* we still think that */ simulation_ended && + (current.get_state() & (Schedulable::state_blocked | + Schedulable::state_terminated)) == 0) + simulation_ended = false; + } + + // 4a. Look for exhausted requests for the running thread + if (running_thread != NULL) + { + bool running_terminated = running_thread->get_state() == Schedulable::state_terminated; + Extender e(new_snapshot, + running_terminated ? Extender::walk_to_sweep : Extender::walk_to_advance, + running_thread->get_elapsed_time()); Requests& reqs = running_thread->get_dynamic_requests(); - for(Requests::iterator r_it = reqs.begin(); r_it != reqs.end(); r_it++) + for (Requests::iterator r_it = reqs.begin(); r_it != reqs.end(); r_it++) e.extendRequest(**r_it); } - // Unblock blocked threads.. by discovering just-now-allocable requests - for(Threads::iterator it = all_threads.begin(); it != all_threads.end(); it++) - { - DynamicThread& current = **it; - + // Unblock blocked threads.. by discovering just-now-allocable requests + for (Threads::iterator it = all_threads.begin(); it != all_threads.end(); it++) + { + DynamicThread& current = **it; + // for each still blocked thread - if(current.get_state() == Schedulable::state_blocked) + if (current.get_state() == Schedulable::state_blocked) { - // Since it was blocked then one and only one (why?) request is unallocable. - // lets' find it and see if our information is outdated (i.e. now it is - // allocable. + // Since it was blocked then one and only one (why?) request is unallocable. + // lets' find it and see if our information is outdated (i.e. now it is + // allocable. bool blocked = false; - // for each request + // for each request Requests& reqs = current.get_dynamic_requests(); - Extender e(new_snapshot, Extender::walk_to_advance, current.get_elapsed_time()); - for(Requests::iterator r_it = reqs.begin(); r_it != reqs.end() && !blocked; r_it++) - { - // update its state. - e.extendRequest(**r_it); - // if it is still unallocable, leave the thread blocked + Extender e(new_snapshot, Extender::walk_to_advance, current.get_elapsed_time()); + for (Requests::iterator r_it = reqs.begin(); r_it != reqs.end() && !blocked; r_it++) + { + // update its state. + e.extendRequest(**r_it); + // if it is still unallocable, leave the thread blocked if ((**r_it).get_state() == Request::state_unallocable) blocked = true; - } - // if no blocked request has been found, the thread is ready. + } + // if no blocked request has been found, the thread is ready. if (!blocked) current.set_state(Schedulable::state_ready); } } - - // ---------- FIXME ---------------- - // Check correctness: Now if the simulation ended we + + // ---------- FIXME ---------------- + // Check correctness: Now if the simulation ended we // append the newly created environment and return false - if(simulation_ended) goto final_cleanup; + if (simulation_ended) goto final_cleanup; - - bool preemptible_policy; - unsigned int time_slice; - try + + bool preemptible_policy; + unsigned int time_slice; + try { - // Temporarily set the _ready_queue param and the _policy one for - // use from external plugins - _policy = &cpu_policy; - _ready_queue = &new_snapshot->get_sorted_queue(); - // ?. Use the policy to sort the queue + // Temporarily set the _ready_queue param and the _policy one for + // use from external plugins + _policy = &cpu_policy; + _ready_queue = &new_snapshot->get_sorted_queue(); + // ?. Use the policy to sort the queue - preemptible_policy = cpu_policy.is_pre_emptive(); - time_slice = cpu_policy.get_time_slice(); - - // ?. See if old running_thread has to be put to ready state - // This happens when the policy makes use of preemptability by - // priority, or when a time slice ended - if(running_thread != NULL && running_thread->get_state() == Schedulable::state_running && - (preemptible_policy || - time_slice == current_instant - running_thread->get_last_acquisition()) ) - { - running_thread->set_state(Schedulable::state_ready); - running_thread->set_last_release(current_instant); - } + preemptible_policy = cpu_policy.is_pre_emptive(); + time_slice = cpu_policy.get_time_slice(); + + // ?. See if old running_thread has to be put to ready state + // This happens when the policy makes use of preemptability by + // priority, or when a time slice ended + if (running_thread != NULL && running_thread->get_state() == Schedulable::state_running && + (preemptible_policy || + time_slice == current_instant - running_thread->get_last_acquisition()) ) + { + running_thread->set_state(Schedulable::state_ready); + running_thread->set_last_release(current_instant); + } @@ -653,102 +652,102 @@ Scheduler::step_forward(History& history, CPUPolicy& cpu_policy) throw(UserInter // ------------------------------- 3 ---------------------------------------- // --------------------------------------------------------------------------------- - // the problem is that a blocked thread is in the ready queue, but here we - // should collect ready threads only. - // an obvious solution is to remove it manually, but hey, we must understand - // what s happening + // the problem is that a blocked thread is in the ready queue, but here we + // should collect ready threads only. + // an obvious solution is to remove it manually, but hey, we must understand + // what s happening - prepare_ready_queue(*new_snapshot, all_threads); - if (_ready_queue->size() != 0) - cpu_policy.sort_queue(); - bool found = false; + prepare_ready_queue(*new_snapshot, all_threads); + if (_ready_queue->size() != 0) + cpu_policy.sort_queue(); + bool found = false; // Try to continue running the current running thread if (running_thread != NULL && running_thread->get_state() == Schedulable::state_running) { - found = true; - // the thread may block on raising a request - Requests& reqs = running_thread->get_dynamic_requests(); - for(Requests::iterator r_it = reqs.begin(); r_it != reqs.end() - && running_thread->get_state() != Schedulable::state_blocked; r_it++) - { - Extender e(new_snapshot, Extender::walk_to_allocate_cpu, running_thread->get_elapsed_time()); - e.extendRequest(**r_it); - if ((**r_it).get_state() == Request::state_unallocable) - { + found = true; + // the thread may block on raising a request + Requests& reqs = running_thread->get_dynamic_requests(); + for (Requests::iterator r_it = reqs.begin(); r_it != reqs.end() + && running_thread->get_state() != Schedulable::state_blocked; r_it++) + { + Extender e(new_snapshot, Extender::walk_to_allocate_cpu, running_thread->get_elapsed_time()); + e.extendRequest(**r_it); + if ((**r_it).get_state() == Request::state_unallocable) + { running_thread->set_state(Schedulable::state_blocked); - found = false; - } - } + found = false; + } + } } // end trying to continue old running thread - // if the old running thread may not directly continue, pick from the ready queue. - //int debug = 1000; - while(_ready_queue->size() != 0 && !found)//&& debug-- > 0); - { - // try with the first on the queue - found = true; - DynamicThread& candidate = (DynamicThread&) _ready_queue->get_item_at(0); + // if the old running thread may not directly continue, pick from the ready queue. + //int debug = 1000; + while (_ready_queue->size() != 0 && !found)//&& debug-- > 0); + { + // try with the first on the queue + found = true; + DynamicThread& candidate = (DynamicThread&) _ready_queue->get_item_at(0); - Requests& reqs = candidate.get_dynamic_requests(); - for(Requests::iterator r_it = reqs.begin(); r_it != reqs.end(); r_it++) - { - Extender e(new_snapshot, Extender::walk_to_allocate_cpu, candidate.get_elapsed_time()); - e.extendRequest(**r_it); - if ((**r_it).get_state() == Request::state_unallocable) - { + Requests& reqs = candidate.get_dynamic_requests(); + for (Requests::iterator r_it = reqs.begin(); r_it != reqs.end(); r_it++) + { + Extender e(new_snapshot, Extender::walk_to_allocate_cpu, candidate.get_elapsed_time()); + e.extendRequest(**r_it); + if ((**r_it).get_state() == Request::state_unallocable) + { candidate.set_state(Schedulable::state_blocked); - // the element is not ready any more, so we must remove it from the queue? - found = false; - } - } - if (found) - { - candidate.set_state(Schedulable::state_running); - candidate.set_last_acquisition(current_instant); - } - _ready_queue->erase_first(); - //cpu_policy.sort_queue(); - } // end picking from ready queue + // the element is not ready any more, so we must remove it from the queue? + found = false; + } + } + if (found) + { + candidate.set_state(Schedulable::state_running); + candidate.set_last_acquisition(current_instant); + } + _ready_queue->erase_first(); + //cpu_policy.sort_queue(); + } // end picking from ready queue - // FIXME - // FIXME - // FIXME - // the following condition is not sufficient. we must also - // be sure that no other processes are ready. - if (!found) - simulation_ended = true; - + // FIXME + // FIXME + // FIXME + // the following condition is not sufficient. we must also + // be sure that no other processes are ready. + if (!found) + simulation_ended = true; - } // end of try - catch(UserInterruptException& e) - { - // Reset values that the policy doesn't need anymore - _policy = NULL; - _ready_queue = NULL; - // Do we need to update/reset something else? + } // end of try + catch (UserInterruptException& e) + { + // Reset values that the policy doesn't need anymore + _policy = NULL; + _ready_queue = NULL; - // Going up unwinding the stack, tell: - // - the user that the policy sucks - // - SimulationController that everything stopped - throw; - } + // Do we need to update/reset something else? - final_cleanup: - - // append the new snapshot... - // ...and remember to release the auto_ptr! - concrete_history.append_new_environment(new_snapshot.release()); + // Going up unwinding the stack, tell: + // - the user that the policy sucks + // - SimulationController that everything stopped + throw; + } - // Reset values that the policy doesn't need anymore - _policy = NULL; - _ready_queue = NULL; +final_cleanup: + + // append the new snapshot... + // ...and remember to release the auto_ptr! + concrete_history.append_new_environment(new_snapshot.release()); + + // Reset values that the policy doesn't need anymore + _policy = NULL; + _ready_queue = NULL; // If we got there, a step has been performed return simulation_ended == false; diff --git a/src/backend/scheduler.hh b/src/backend/scheduler.hh index 7a80572..6d44d83 100644 --- a/src/backend/scheduler.hh +++ b/src/backend/scheduler.hh @@ -41,7 +41,7 @@ namespace sgpem namespace sgpem { class Scheduler; - + /** \brief Manages the DynamicSchedulable objects, implementing a given policy. @@ -69,13 +69,13 @@ namespace sgpem Resets the simulation to the initial state. */ void reset_status(); - /** - Generates a new ReadyQueue representing the status of the processes - at the simulation instant next to the current one, and extends the History by - one instant with it. + /** + Generates a new ReadyQueue representing the status of the processes + at the simulation instant next to the current one, and extends the History by + one instant with it. - \return false If the simulation has ended, true otherwise - */ + \return false If the simulation has ended, true otherwise + */ bool step_forward(History& history, CPUPolicy& cpu_policy) throw(UserInterruptException); /** @@ -84,9 +84,9 @@ namespace sgpem */ CPUPolicy* get_policy(); - private: + private: Scheduler(); //private constructor. - + ReadyQueue* _ready_queue; CPUPolicy* _policy; diff --git a/src/backend/serialize_visitor.hh b/src/backend/serialize_visitor.hh index 23380cf..20c32a2 100644 --- a/src/backend/serialize_visitor.hh +++ b/src/backend/serialize_visitor.hh @@ -68,29 +68,29 @@ namespace sgpem BUG: a resource must be saved with her own associated key. */ virtual void from_resource(const Resource& obj) throw(SerializerError) = 0; - + /** \brief Add output to the serializer taking data from resource and key BUG FIXED: This save a resource with her own associated key. */ virtual void from_resource(const Resource& obj, const Glib::ustring& key) throw(SerializerError) = 0; - + /** \brief Add output to the serializer taking data from process */ virtual void from_process(const Process& obj) throw(SerializerError) = 0; - + /** \brief Add output to the serializer taking data from thread */ virtual void from_thread(const Thread& obj) throw(SerializerError) = 0; - + /** \brief Add output to the serializer taking data from request */ virtual void from_request(const Request& obj) throw(SerializerError) = 0; - + /** \brief Add output to the serializer taking data from subrequest */ diff --git a/src/backend/serializer.cc b/src/backend/serializer.cc index 656b487..a4c6808 100644 --- a/src/backend/serializer.cc +++ b/src/backend/serializer.cc @@ -27,7 +27,7 @@ using namespace sgpem; Serializer::Serializer() { SerializersGatekeeper::get_instance().register_serializer(this); -} +} Serializer::~Serializer() {} diff --git a/src/backend/serializer.hh b/src/backend/serializer.hh index 96356c3..3605687 100644 --- a/src/backend/serializer.hh +++ b/src/backend/serializer.hh @@ -34,7 +34,7 @@ namespace sgpem class SG_DLLEXPORT Serializer { public: - Serializer(); + Serializer(); virtual ~Serializer() = 0; virtual void save_snapshot(const Glib::ustring& filename, const History& hist) throw(SerializerError) = 0; diff --git a/src/backend/serializer_error.cc b/src/backend/serializer_error.cc index 232b441..fa1fb45 100644 --- a/src/backend/serializer_error.cc +++ b/src/backend/serializer_error.cc @@ -25,6 +25,5 @@ using namespace sgpem; SerializerError::SerializerError(const std::string& what) : - std::runtime_error(what) -{ -} + std::runtime_error(what) +{} diff --git a/src/backend/serializer_error.hh b/src/backend/serializer_error.hh index 63824d9..b53bef6 100644 --- a/src/backend/serializer_error.hh +++ b/src/backend/serializer_error.hh @@ -31,7 +31,8 @@ namespace sgpem { public: SerializerError(const std::string& what); - }; //~ class SerializerError + } + ; //~ class SerializerError } //~ namespace sgpem diff --git a/src/backend/serializers_gatekeeper.cc b/src/backend/serializers_gatekeeper.cc index ca633d7..05942c9 100644 --- a/src/backend/serializers_gatekeeper.cc +++ b/src/backend/serializers_gatekeeper.cc @@ -52,7 +52,7 @@ SerializersGatekeeper::register_serializer(Serializer* serializer) SerializerIterator end = _registered.end(); - if(find(_registered.begin(), end, serializer) == end) + if (find(_registered.begin(), end, serializer) == end) _registered.push_back(serializer); } @@ -64,7 +64,7 @@ SerializersGatekeeper::unregister_serializer(Serializer* serializer) SerializerIterator end = _registered.end(); SerializerIterator pos = find(_registered.begin(), end, serializer); - if(pos != end) + if (pos != end) { _registered.erase(pos); } diff --git a/src/backend/simulation.cc b/src/backend/simulation.cc index 9966869..cf7a0c7 100644 --- a/src/backend/simulation.cc +++ b/src/backend/simulation.cc @@ -30,8 +30,7 @@ template class SG_DLLEXPORT Singleton; Simulation::~Simulation() -{ -} +{} Simulation& Simulation::get_instance() diff --git a/src/backend/simulation.hh b/src/backend/simulation.hh index 5abcc72..3f522e5 100644 --- a/src/backend/simulation.hh +++ b/src/backend/simulation.hh @@ -68,9 +68,9 @@ namespace sgpem state_paused, state_stopped }; - + virtual ~Simulation(); - + /** \brief Runs the simulation. @@ -109,7 +109,7 @@ namespace sgpem \see set_timer() */ virtual int get_timer() const = 0; - + /** \brief This methods allows to change the way the simulation progresses. @@ -128,7 +128,7 @@ namespace sgpem virtual bool get_mode() const = 0; virtual state get_state() const = 0; - + /** \brief Setup the policy to be used by the system. */ @@ -140,7 +140,7 @@ namespace sgpem virtual CPUPolicy* get_policy() = 0; virtual History& get_history() = 0; - + /** * Small kludge to avoid the need for declaration of ConcreteSimulation * by the calling code of Simulation::get_instance() diff --git a/src/backend/static_process.cc b/src/backend/static_process.cc index d300d5d..5a0a248 100644 --- a/src/backend/static_process.cc +++ b/src/backend/static_process.cc @@ -23,7 +23,7 @@ using namespace sgpem; StaticProcess::StaticProcess(const Glib::ustring& name, const unsigned int& arrival, const int& priority) - : StaticSchedulable(name, priority), _start_time(arrival) + : StaticSchedulable(name, priority), _start_time(arrival) {} @@ -34,24 +34,24 @@ StaticProcess::~StaticProcess() unsigned int StaticProcess::get_arrival_time() const { - return _start_time; + return _start_time; } unsigned int StaticProcess::get_total_cpu_time() const { - typedef std::vector::const_iterator ThreadIterator; + typedef std::vector::const_iterator ThreadIterator; - unsigned int result = 0; - for(ThreadIterator it = _threads.begin(); it != _threads.end(); it++) - result += (*it)->get_total_cpu_time(); - return result; + unsigned int result = 0; + for (ThreadIterator it = _threads.begin(); it != _threads.end(); it++) + result += (*it)->get_total_cpu_time(); + return result; } -std::vector& +std::vector& StaticProcess::get_threads() { - return _threads; + return _threads; } diff --git a/src/backend/static_process.hh b/src/backend/static_process.hh index 7c77a13..23dc9a8 100644 --- a/src/backend/static_process.hh +++ b/src/backend/static_process.hh @@ -47,17 +47,17 @@ namespace sgpem /** \brief Destructor. */ virtual ~StaticProcess(); - virtual unsigned int get_total_cpu_time() const; - virtual unsigned int get_arrival_time() const; + virtual unsigned int get_total_cpu_time() const; + virtual unsigned int get_arrival_time() const; - // Does the job also of add_thread() and remove_thread(). :-) - // Since we're touching backend internals, we can do this safely - // (because we know what we're doing, isn't it?) - virtual std::vector& get_threads(); + // Does the job also of add_thread() and remove_thread(). :-) + // Since we're touching backend internals, we can do this safely + // (because we know what we're doing, isn't it?) + virtual std::vector& get_threads(); private: - unsigned int _start_time; - std::vector _threads; + unsigned int _start_time; + std::vector _threads; }; } diff --git a/src/backend/static_request.cc b/src/backend/static_request.cc index a1d1127..3286a29 100644 --- a/src/backend/static_request.cc +++ b/src/backend/static_request.cc @@ -31,14 +31,14 @@ StaticRequest::StaticRequest(StaticThread* thread, _thread(thread), _instant(instant) { assert(thread != NULL); - _thread->get_requests().push_back(this); + _thread->get_requests().push_back(this); } StaticRequest::~StaticRequest() { - typedef std::vector Requests; - Requests& siblings = _thread->get_requests(); - siblings.erase(find(siblings.begin(), siblings.end(), this)); + typedef std::vector Requests; + Requests& siblings = _thread->get_requests(); + siblings.erase(find(siblings.begin(), siblings.end(), this)); } unsigned int diff --git a/src/backend/static_schedulable.hh b/src/backend/static_schedulable.hh index daea108..f6c85cd 100644 --- a/src/backend/static_schedulable.hh +++ b/src/backend/static_schedulable.hh @@ -68,7 +68,7 @@ namespace sgpem * user, that allows it to be quickly recognized. */ virtual const Glib::ustring& get_name() const; - + private: Glib::ustring _name; int _priority; diff --git a/src/backend/static_sub_request.cc b/src/backend/static_sub_request.cc index db7e739..428414a 100644 --- a/src/backend/static_sub_request.cc +++ b/src/backend/static_sub_request.cc @@ -38,7 +38,7 @@ StaticSubRequest::StaticSubRequest(resource_key_t resource_key, } -StaticSubRequest::~StaticSubRequest() +StaticSubRequest::~StaticSubRequest() { // See comment in constructor. diff --git a/src/backend/static_thread.cc b/src/backend/static_thread.cc index db4c2a5..4ed410d 100644 --- a/src/backend/static_thread.cc +++ b/src/backend/static_thread.cc @@ -29,23 +29,23 @@ using namespace std; StaticThread::StaticThread(const Glib::ustring& name, StaticProcess& process, - unsigned int cpu_time, + unsigned int cpu_time, unsigned int arrival_time, int base_priority) : StaticSchedulable(name, base_priority), - _start_time_delta(arrival_time), - _required_cpu_time(cpu_time), + _start_time_delta(arrival_time), + _required_cpu_time(cpu_time), _process(&process) { - process.get_threads().push_back(this); + process.get_threads().push_back(this); } StaticThread::~StaticThread() { - typedef std::vector Threads; - Threads& siblings = _process->get_threads(); - siblings.erase(find(siblings.begin(), siblings.end(), this)); + typedef std::vector Threads; + Threads& siblings = _process->get_threads(); + siblings.erase(find(siblings.begin(), siblings.end(), this)); } @@ -70,5 +70,5 @@ StaticThread::get_process() std::vector& StaticThread::get_requests() { - return _static_requests; + return _static_requests; } diff --git a/src/backend/static_thread.hh b/src/backend/static_thread.hh index 257e0e7..f1a04f8 100644 --- a/src/backend/static_thread.hh +++ b/src/backend/static_thread.hh @@ -42,11 +42,11 @@ namespace sgpem public: StaticThread(const Glib::ustring& name, StaticProcess& process, - unsigned int cpu_time, + unsigned int cpu_time, unsigned int arrival_time = 0, int base_priority = 0); - virtual ~StaticThread(); + virtual ~StaticThread(); virtual unsigned int get_total_cpu_time() const; @@ -54,11 +54,11 @@ namespace sgpem virtual StaticProcess& get_process(); - // Caller can use directly the vector instead that - // the "remove_request()" and "add_request()" method - // of the design. Since this class is internal to the - // backend anyway, this is okay. - virtual std::vector& get_requests(); + // Caller can use directly the vector instead that + // the "remove_request()" and "add_request()" method + // of the design. Since this class is internal to the + // backend anyway, this is okay. + virtual std::vector& get_requests(); private: StaticThread(const StaticThread&); diff --git a/src/backend/string_utils.cc b/src/backend/string_utils.cc index 5ed29cf..58771bc 100644 --- a/src/backend/string_utils.cc +++ b/src/backend/string_utils.cc @@ -29,210 +29,210 @@ using Glib::ustring; namespace sgpem { - /* Force template instantiation to allow visibility outside this DSO */ -template SG_DLLEXPORT int string_to(const Glib::ustring&); -template SG_DLLEXPORT float string_to(const Glib::ustring&); + /* Force template instantiation to allow visibility outside this DSO */ + template SG_DLLEXPORT int string_to(const Glib::ustring&); + template SG_DLLEXPORT float string_to(const Glib::ustring&); - // Specialized further down in this file: - // template SG_DLLEXPORT bool string_to(const Glib::ustring&); + // Specialized further down in this file: + // template SG_DLLEXPORT bool string_to(const Glib::ustring&); -/** - \brief A function that converts a Unicode string to an integer value - - The string can contain ONLY digits and the "minus" character. - - \returns TRUE if the string is well formatted - \returns FALSE otherwise -*/ -bool -string_to_int(const ustring& str, int& num) -{ - static const ustring allvalid = "0123456789-"; - static const ustring digits = "0123456789"; + /** + \brief A function that converts a Unicode string to an integer value - // the string can't be empty - if (str.length() == 0 || (str.length() == 1 && str[0] == '-')) - return false; + The string can contain ONLY digits and the "minus" character. - //checks if the string contains only digits - if (str.find_first_not_of(allvalid) < str.length()) - return false; - if (str.substr(1).find_first_not_of(digits) < str.length() - 1) - return false; - - num = 0; - int multiplier = 1, val; - int start; //the position of the biggest digit - if (str[0] == '-') - start = 1; - else - start = 0; - for (int pos = str.length() - 1; pos >= start ; pos--) + \returns TRUE if the string is well formatted + \returns FALSE otherwise + */ + bool + string_to_int(const ustring& str, int& num) { - val = str[pos] - 48; //the INTEGER value of the digit - num += val * multiplier; - multiplier *= 10; - } - //if there is the minus then multiply for -1 - if (start == 1) - num *= -1; - return true; -} + static const ustring allvalid = "0123456789-"; + static const ustring digits = "0123456789"; -template -T -string_to(const ustring& str) throw(domain_error) -{ - if(tokenize(str).size() != 1) - throw domain_error(_("too few or too many tokens")); + // the string can't be empty + if (str.length() == 0 || (str.length() == 1 && str[0] == '-')) + return false; - istringstream iss(str); + //checks if the string contains only digits + if (str.find_first_not_of(allvalid) < str.length()) + return false; + if (str.substr(1).find_first_not_of(digits) < str.length() - 1) + return false; - iss.exceptions(ios_base::failbit | ios_base::badbit); - - T value; - - try - { - iss >> value; - } - catch(ios_base::failure e) - { - throw domain_error(e.what()); - } - - // disable exceptions, otherwise peek() will throw them! - // how useless!!! - iss.exceptions(ios_base::goodbit); - - if(iss.peek() != istringstream::traits_type::eof()) - throw domain_error(_("incorrect number format")); - - return value; -} - -template <> -SG_DLLEXPORT bool -string_to(const Glib::ustring& str) throw(domain_error) -{ - if(tokenize(str).size() != 1) - throw domain_error(_("too few or too many tokens")); - - istringstream iss(str); - - iss.exceptions(ios_base::failbit | ios_base::badbit); - - bool value; - - try - { - iss >> boolalpha >> value; - } - catch(ios_base::failure e) - { - throw domain_error(e.what()); - } - - // disable exceptions, otherwise peek() will throw them! - // how useless!!! - iss.exceptions(ios_base::goodbit); - - if(iss.peek() != istringstream::traits_type::eof()) - throw domain_error(_("incorrect boolean")); - - return value; -} - -/** - \brief A function that converts an integer value to an Unicode string - */ -void -int_to_string(const int& num, ustring& str) -{ - if (num == 0) - { - str = '0'; - return; - } - - str = ""; - int val = num; - bool negative = (val < 0) ? true : false; - if (negative) val *= -1; - - while (true) - { - str = char(val % 10 + 48) + str; - if (val > 1 && val / 10 != 0) - val /= 10; + num = 0; + int multiplier = 1, val; + int start; //the position of the biggest digit + if (str[0] == '-') + start = 1; else - break; + start = 0; + for (int pos = str.length() - 1; pos >= start ; pos--) + { + val = str[pos] - 48; //the INTEGER value of the digit + num += val * multiplier; + multiplier *= 10; + } + //if there is the minus then multiply for -1 + if (start == 1) + num *= -1; + return true; } - if (negative) - str = '-' + str; -} -void -float_to_string(const float& f, Glib::ustring& str) -{ - stringstream ss; - ss << f; - char p[20]; - ss.getline(p, 20); - str = p; -} + template + T + string_to(const ustring& str) throw(domain_error) + { + if (tokenize(str).size() != 1) + throw domain_error(_("too few or too many tokens")); -void -string_to_float(const Glib::ustring& str, float& f) -{ - stringstream ss; - ss << str; - ss >> f; -} + istringstream iss(str); + + iss.exceptions(ios_base::failbit | ios_base::badbit); + + T value; + + try + { + iss >> value; + } + catch (ios_base::failure e) + { + throw domain_error(e.what()); + } + + // disable exceptions, otherwise peek() will throw them! + // how useless!!! + iss.exceptions(ios_base::goodbit); + + if (iss.peek() != istringstream::traits_type::eof()) + throw domain_error(_("incorrect number format")); + + return value; + } + + template <> + SG_DLLEXPORT bool + string_to(const Glib::ustring& str) throw(domain_error) + { + if (tokenize(str).size() != 1) + throw domain_error(_("too few or too many tokens")); + + istringstream iss(str); + + iss.exceptions(ios_base::failbit | ios_base::badbit); + + bool value; + + try + { + iss >> boolalpha >> value; + } + catch (ios_base::failure e) + { + throw domain_error(e.what()); + } + + // disable exceptions, otherwise peek() will throw them! + // how useless!!! + iss.exceptions(ios_base::goodbit); + + if (iss.peek() != istringstream::traits_type::eof()) + throw domain_error(_("incorrect boolean")); + + return value; + } + + /** + \brief A function that converts an integer value to an Unicode string + */ + void + int_to_string(const int& num, ustring& str) + { + if (num == 0) + { + str = '0'; + return; + } + + str = ""; + int val = num; + bool negative = (val < 0) ? true : false; + if (negative) val *= -1; + + while (true) + { + str = char(val % 10 + 48) + str; + if (val > 1 && val / 10 != 0) + val /= 10; + else + break; + } + if (negative) + str = '-' + str; + } + + void + float_to_string(const float& f, Glib::ustring& str) + { + stringstream ss; + ss << f; + char p[20]; + ss.getline(p, 20); + str = p; + } + + void + string_to_float(const Glib::ustring& str, float& f) + { + stringstream ss; + ss << str; + ss >> f; + } // helper function for tokenize() -static void -add_token(Tokens& tokens, const ustring& token) -{ - if(token.size() > 0) - tokens.push_back(token); -} - -Tokens -tokenize(const ustring& str) -{ - istringstream iss(str); - Tokens tokens; - - while(iss) + static void + add_token(Tokens& tokens, const ustring& token) { - ustring token; - iss >> token; - - ustring::size_type index; - - // for the SET command, parse the assigment symbol as - // a separate token - do - { - index = token.find('='); - - if(index != ustring::npos) - { - add_token(tokens, token.substr(0, index)); - add_token(tokens, "="); - - // the second argument can safely be out of range - token = token.substr(index + 1, token.size()); - } - } - while(index != ustring::npos); - - add_token(tokens, token); + if (token.size() > 0) + tokens.push_back(token); } - return tokens; -} + Tokens + tokenize(const ustring& str) + { + istringstream iss(str); + Tokens tokens; + + while (iss) + { + ustring token; + iss >> token; + + ustring::size_type index; + + // for the SET command, parse the assigment symbol as + // a separate token + do + { + index = token.find('='); + + if (index != ustring::npos) + { + add_token(tokens, token.substr(0, index)); + add_token(tokens, "="); + + // the second argument can safely be out of range + token = token.substr(index + 1, token.size()); + } + } + while (index != ustring::npos); + + add_token(tokens, token); + } + + return tokens; + } } diff --git a/src/backend/string_utils.hh b/src/backend/string_utils.hh index faaa303..306e843 100644 --- a/src/backend/string_utils.hh +++ b/src/backend/string_utils.hh @@ -31,7 +31,7 @@ namespace sgpem { typedef std::vector Tokens; - + /**\brief This function tries to convert a string into an integer value. The string can contain only digits and the minus character (for negative numbers). diff --git a/src/backend/sub_request.hh b/src/backend/sub_request.hh index c8914be..bfbb9c0 100644 --- a/src/backend/sub_request.hh +++ b/src/backend/sub_request.hh @@ -34,24 +34,24 @@ namespace sgpem class SG_DLLEXPORT SubRequest { public: - typedef int resource_key_t; - typedef Request::state state; + typedef int resource_key_t; + typedef Request::state state; virtual ~SubRequest(); - virtual bool operator==(const SubRequest& op2) const = 0; + virtual bool operator==(const SubRequest& op2) const = 0; virtual resource_key_t get_resource_key() const = 0; - virtual unsigned int get_length() const = 0; + virtual unsigned int get_length() const = 0; virtual int get_queue_position() const = 0; - virtual state get_state() const = 0; + virtual state get_state() const = 0; - virtual unsigned int get_remaining_time() const = 0; + virtual unsigned int get_remaining_time() const = 0; - virtual Request& get_request() = 0; + virtual Request& get_request() = 0; virtual void serialize(SerializeVisitor& translator) const = 0; }; diff --git a/src/backend/thread.hh b/src/backend/thread.hh index 9ff4f3d..d5410ab 100644 --- a/src/backend/thread.hh +++ b/src/backend/thread.hh @@ -38,7 +38,7 @@ namespace sgpem public: virtual ~Thread(); - virtual Process& get_process() = 0; + virtual Process& get_process() = 0; virtual std::vector get_requests() = 0; virtual void serialize(SerializeVisitor& translator) const = 0; }; diff --git a/src/cairo_elements.cc b/src/cairo_elements.cc index 5290f2e..74de67e 100644 --- a/src/cairo_elements.cc +++ b/src/cairo_elements.cc @@ -26,12 +26,11 @@ using namespace sgpem; CairoElements::CairoElements(cairo_t* const ctx) - : _ctx(ctx) -{ -} + : _ctx(ctx) +{} -void +void CairoElements::draw_3dsphere(const Point& center, float radius, const Color& cl) { cairo_t*& cr = _ctx; @@ -40,7 +39,7 @@ CairoElements::draw_3dsphere(const Point& center, float radius, const Color& cl) const float& r = cl.r; const float& g = cl.g; const float& b = cl.b; - + // Draw initial sphere perimeter cairo_save(cr); cairo_new_path(cr); @@ -55,35 +54,35 @@ CairoElements::draw_3dsphere(const Point& center, float radius, const Color& cl) cairo_set_line_width(cr, radius * .01); cairo_stroke(cr); cairo_restore(cr); - + // Internal gradient cairo_save(cr); grad = cairo_pattern_create_linear(x, y, x, y + radius); cairo_pattern_add_color_stop_rgba(grad, 1, r - .4, g - .4, b - .4, 1); cairo_pattern_add_color_stop_rgba(grad, 0, r, g, b, .7); cairo_set_source(cr, grad); - cairo_translate(cr, x*.2, (y + radius*8/9) * 1/3); - cairo_scale(cr, .8, 2./3); + cairo_translate(cr, x*.2, (y + radius*8 / 9) * 1 / 3); + cairo_scale(cr, .8, 2. / 3); cairo_arc(cr, x, y, radius, 0, 2*M_PI); cairo_fill(cr); cairo_pattern_destroy(grad); cairo_restore(cr); - + // Internal glow cairo_save(cr); grad = cairo_pattern_create_linear(x, y - radius, x, y); cairo_pattern_add_color_stop_rgba(grad, 0, 1, 1, 1, .9); cairo_pattern_add_color_stop_rgba(grad, 1, 1, 1, 1, .2); cairo_set_source(cr, grad); - cairo_translate(cr, x * .2, (y - radius*8/9) * 1/3); - cairo_scale(cr, .8, 2./3); + cairo_translate(cr, x * .2, (y - radius*8 / 9) * 1 / 3); + cairo_scale(cr, .8, 2. / 3); cairo_arc(cr, x, y, radius, 0, 2*M_PI); cairo_fill(cr); cairo_pattern_destroy(grad); - cairo_restore(cr); + cairo_restore(cr); } -void +void CairoElements::draw_3dcube(const Rectangle& area, const Color& cl) { cairo_t*& cr = _ctx; @@ -97,7 +96,7 @@ CairoElements::draw_3dcube(const Rectangle& area, const Color& cl) } -void +void CairoElements::draw_container(const Rectangle& area) { cairo_t*& cr = _ctx; @@ -105,27 +104,27 @@ CairoElements::draw_container(const Rectangle& area) const float& y0 = area.y0; const float& w = area.w; const float& h = area.h; - + const double corner_radius = 0.05; - + cairo_save(cr); cairo_new_path(cr); cairo_move_to(cr, x0 + corner_radius, y0); - + // NW -> NE - cairo_line_to(cr, x0+w - corner_radius, y0); - cairo_curve_to(cr, x0+w, y0, x0+w, y0, x0+w, y0 + corner_radius); + cairo_line_to(cr, x0 + w - corner_radius, y0); + cairo_curve_to(cr, x0 + w, y0, x0 + w, y0, x0 + w, y0 + corner_radius); // NE -> SE - cairo_line_to(cr, x0+w, y0+h - corner_radius); - cairo_curve_to(cr, x0+w, y0+h, x0+w, y0+h, x0+w - corner_radius, y0+h); + cairo_line_to(cr, x0 + w, y0 + h - corner_radius); + cairo_curve_to(cr, x0 + w, y0 + h, x0 + w, y0 + h, x0 + w - corner_radius, y0 + h); // SE -> SW - cairo_line_to(cr, x0 + corner_radius, y0+h); - cairo_curve_to(cr, x0, y0+h, x0, y0+h, x0, y0+h - corner_radius); + cairo_line_to(cr, x0 + corner_radius, y0 + h); + cairo_curve_to(cr, x0, y0 + h, x0, y0 + h, x0, y0 + h - corner_radius); // SW -> NW cairo_line_to(cr, x0, y0 + corner_radius); cairo_curve_to(cr, x0, y0, x0, y0, x0 + corner_radius, y0); cairo_close_path(cr); - + cairo_set_source_rgb(cr, 1, 1, 0.9); cairo_fill_preserve(cr); @@ -137,7 +136,7 @@ CairoElements::draw_container(const Rectangle& area) } -void +void CairoElements::draw_expandable(const Rectangle& area, bool expanded) { cairo_t*& cr = _ctx; @@ -145,42 +144,40 @@ CairoElements::draw_expandable(const Rectangle& area, bool expanded) const float& y0 = area.y0; const float& w = area.w; const float& h = area.h; - + cairo_save(cr); cairo_set_line_width(cr, .005); cairo_set_source_rgb(cr, 1, 1, 1); - + cairo_new_path(cr); cairo_rectangle(cr, x0, y0, w, h); cairo_set_source_rgb(cr, 1, 1, 1); cairo_fill_preserve(cr); cairo_set_source_rgb(cr, 0, 0, 0); cairo_stroke(cr); - - cairo_move_to(cr, x0 + w/10, y0 + h/2); - cairo_line_to(cr, x0 + w*9/10, y0 + h/2); + + cairo_move_to(cr, x0 + w / 10, y0 + h / 2); + cairo_line_to(cr, x0 + w*9 / 10, y0 + h / 2); cairo_stroke(cr); - - if(!expanded) - { - cairo_move_to(cr, x0 + w/2, y0 + h/10); - cairo_line_to(cr, x0 + w/2, y0 + h*9/10); - cairo_stroke(cr); - } - + + if (!expanded) + { + cairo_move_to(cr, x0 + w / 2, y0 + h / 10); + cairo_line_to(cr, x0 + w / 2, y0 + h*9 / 10); + cairo_stroke(cr); + } + cairo_restore(cr); } -Rectangle draw_thread_status(const Point& top_left_crn, +Rectangle draw_thread_status(const Point& top_left_crn, const Thread& thread_info) -{ -} +{} Rectangle draw_process_status(const Point& top_left_crn, const Process& process_info) -{ -} +{} diff --git a/src/cairo_elements.hh b/src/cairo_elements.hh index a2a3830..ca30b42 100644 --- a/src/cairo_elements.hh +++ b/src/cairo_elements.hh @@ -57,13 +57,13 @@ namespace sgpem { public: CairoElements(cairo_t* const ctx); - + void draw_3dsphere(const Point& center, float radius, const Color& cl); void draw_3dcube(const Rectangle& area, const Color& cl); void draw_container(const Rectangle& area); void draw_expandable(const Rectangle& area, bool expanded = false); - Rectangle draw_thread_status(const Point& top_left_crn, + Rectangle draw_thread_status(const Point& top_left_crn, const Thread& thread_info); Rectangle draw_process_status(const Point& top_left_crn, const Process& process_info); diff --git a/src/cairo_widget.cc b/src/cairo_widget.cc index 4656efd..3d28e0b 100644 --- a/src/cairo_widget.cc +++ b/src/cairo_widget.cc @@ -34,14 +34,14 @@ using namespace sgpem; CairoWidget::CairoWidget() - : Glib::ObjectBase("sgpem_CairoWidget"), - Gtk::Widget(), _h(1), _buf(NULL) + : Glib::ObjectBase("sgpem_CairoWidget"), + Gtk::Widget(), _h(1), _buf(NULL) { set_flags(Gtk::NO_WINDOW); // Register this observer: Simulation::get_instance().get_history().attach(*this); } - + CairoWidget::~CairoWidget() { @@ -49,12 +49,12 @@ CairoWidget::~CairoWidget() } -void +void CairoWidget::update(const History& history) { // get_window() returns a null pointer // if the widget has not been realized - if(!is_realized()) + if (!is_realized()) return; // Nowhere to draw to. // Determine the final height before to start drawing @@ -66,11 +66,11 @@ CairoWidget::update(const History& history) // Draw the widget background as the first thing. // I've seen this is how it's done in the very Gtk+ toolkit // for the GtkProgressBar widget. - GtkStyle* gStyle = get_style()->gobj(); - gtk_paint_box(gStyle, _buf->gobj(), - GTK_STATE_NORMAL, GTK_SHADOW_ETCHED_IN, + GtkStyle* gStyle = get_style()->gobj(); + gtk_paint_box(gStyle, _buf->gobj(), + GTK_STATE_NORMAL, GTK_SHADOW_ETCHED_IN, NULL, this->gobj(), "through", - 0, 0, w, _h); + 0, 0, w, _h); cairo_t* ctx = gdk_cairo_create(_buf->gobj()); @@ -86,10 +86,10 @@ CairoWidget::update(const History& history) } -void +void CairoWidget::on_realize() { - if(is_realized()) return; + if (is_realized()) return; Gtk::Widget::on_realize(); ensure_style(); @@ -97,32 +97,32 @@ CairoWidget::on_realize() GdkWindowAttr attributes; memset(&attributes, 0, sizeof(attributes)); - Gtk::Allocation alloc = get_allocation(); + Gtk::Allocation alloc = get_allocation(); - attributes.x = alloc.get_x(); - attributes.y = alloc.get_y(); - attributes.width = alloc.get_width(); - attributes.height = alloc.get_height(); - attributes.wclass = GDK_INPUT_OUTPUT; + attributes.x = alloc.get_x(); + attributes.y = alloc.get_y(); + attributes.width = alloc.get_width(); + attributes.height = alloc.get_height(); + attributes.wclass = GDK_INPUT_OUTPUT; attributes.event_mask = get_events() | GDK_EXPOSURE_MASK; attributes.window_type = GDK_WINDOW_CHILD; attributes.visual = get_visual()->gobj(); attributes.colormap = get_colormap()->gobj(); - static const gint attributes_mask = Gdk::WA_X | Gdk::WA_Y | Gdk::WA_WMCLASS - | Gdk::WA_VISUAL | Gdk::WA_COLORMAP; + static const gint attributes_mask = Gdk::WA_X | Gdk::WA_Y | Gdk::WA_WMCLASS + | Gdk::WA_VISUAL | Gdk::WA_COLORMAP; - Glib::RefPtr window = Gdk::Window::create(get_parent_window(), - &attributes, - attributes_mask); + Glib::RefPtr window = Gdk::Window::create(get_parent_window(), + &attributes, + attributes_mask); unset_flags(Gtk::NO_WINDOW); - set_window(window); - window->set_user_data(gobj()); - + set_window(window); + window->set_user_data(gobj()); + // Not sure if the following line is needed: gtk_style_attach(get_style()->gobj(), window->gobj()); - get_style()->set_background(window, Gtk::STATE_ACTIVE); + get_style()->set_background(window, Gtk::STATE_ACTIVE); } void @@ -130,46 +130,46 @@ CairoWidget::on_size_request(Gtk::Requisition* requisition) { // FIXME: take correct measures, consider also using a viewport(?) *requisition = Gtk::Requisition(); - requisition->width = get_allocation().get_width(); - requisition->height = _h; + requisition->width = get_allocation().get_width(); + requisition->height = _h; } void CairoWidget::on_size_allocate(const Gtk::Allocation& allocation) { - set_allocation(allocation); - - if(is_realized()) - get_window()->move_resize(allocation.get_x(), allocation.get_y(), - allocation.get_width(), allocation.get_height()); + set_allocation(allocation); + + if (is_realized()) + get_window()->move_resize(allocation.get_x(), allocation.get_y(), + allocation.get_width(), allocation.get_height()); } -bool +bool CairoWidget::on_expose_event(GdkEventExpose* event) { - if(event == NULL || event->count > 0) + if (event == NULL || event->count > 0) return false; // calculated dinamically: int w = get_allocation().get_width(); set_size_request(w, _h); - + // Clip to redraw only the smallest possible area // Use double buffering or we're CPU-dead // Copy from the buffer to the screen - if(_buf) - get_window()->draw_drawable(get_style()->get_black_gc(), _buf, - event->area.x, event->area.y, + if (_buf) + get_window()->draw_drawable(get_style()->get_black_gc(), _buf, + event->area.x, event->area.y, event->area.x, event->area.y, event->area.width, event->area.height); - + return true; } -bool +bool CairoWidget::on_button_press_event(GdkEventButton* event) { // Not here. Yet. diff --git a/src/cairo_widget.hh b/src/cairo_widget.hh index aa085fe..e6a6341 100644 --- a/src/cairo_widget.hh +++ b/src/cairo_widget.hh @@ -40,8 +40,8 @@ namespace sgpem void update(const History& history); protected: - virtual void on_realize(); - virtual void on_size_allocate(const Gtk::Allocation& allocation); + virtual void on_realize(); + virtual void on_size_allocate(const Gtk::Allocation& allocation); virtual void on_size_request(Gtk::Requisition* requisition); virtual bool on_expose_event(GdkEventExpose* event); virtual bool on_button_press_event(GdkEventButton* event); @@ -53,7 +53,7 @@ namespace sgpem typedef std::pair area_callback_t; typedef std::vector areas_vect_t; - private: + private: // The height the widget will assume, must be determined // before starting drawing by calc_height() unsigned int _h; diff --git a/src/gui_builder.cc b/src/gui_builder.cc index d14d3aa..74d85e8 100644 --- a/src/gui_builder.cc +++ b/src/gui_builder.cc @@ -48,56 +48,55 @@ test_me() GuiBuilder::GuiBuilder(const std::string& gladefile) - : _refXml(Xml::create(gladefile)) + : _refXml(Xml::create(gladefile)) { - using namespace Gtk; + using namespace Gtk; - Window& main_window = get_initial_window(); + Window& main_window = get_initial_window(); - // Connect extra signals (decide where to do this... - // here -- ugly -- derive widgets and then use - // Glade::Xml::get_widget_derived -- better --) - MenuItem* file_quit = NULL; - _refXml->get_widget("MenuItem.File.Quit", file_quit); - file_quit->signal_activate().connect(sigc::ptr_fun(&Main::quit)); + // Connect extra signals (decide where to do this... + // here -- ugly -- derive widgets and then use + // Glade::Xml::get_widget_derived -- better --) + MenuItem* file_quit = NULL; + _refXml->get_widget("MenuItem.File.Quit", file_quit); + file_quit->signal_activate().connect(sigc::ptr_fun(&Main::quit)); - // About dialog - MenuItem* help_about = NULL; - _refXml->get_widget("MenuItem.Help.About", help_about); - AboutDialog* about_dialog = NULL; - _refXml->get_widget("AboutDialog", about_dialog); - //help_about->signal_activate().connect(sigc::mem_fun(*about_dialog, &Window::show)); + // About dialog + MenuItem* help_about = NULL; + _refXml->get_widget("MenuItem.Help.About", help_about); + AboutDialog* about_dialog = NULL; + _refXml->get_widget("AboutDialog", about_dialog); + //help_about->signal_activate().connect(sigc::mem_fun(*about_dialog, &Window::show)); help_about->signal_activate().connect(sigc::ptr_fun(test_me)); - // Temporary code to test the Schedulables custom widget - Expander* scheds_expander = NULL; - _refXml->get_widget("SchedulablesExpander", scheds_expander); - SchedulablesWidget* scheds_widget = manage(new SchedulablesWidget()); - scheds_expander->add(*scheds_widget); - // we have to remember to manually show custom added widgets: - scheds_widget->show(); + // Temporary code to test the Schedulables custom widget + Expander* scheds_expander = NULL; + _refXml->get_widget("SchedulablesExpander", scheds_expander); + SchedulablesWidget* scheds_widget = manage(new SchedulablesWidget()); + scheds_expander->add(*scheds_widget); + // we have to remember to manually show custom added widgets: + scheds_widget->show(); } -GuiBuilder::~GuiBuilder() -{ -} +GuiBuilder::~GuiBuilder() +{} Gtk::Window& GuiBuilder::get_initial_window() const { - Gtk::Window* main_window = NULL; - _refXml->get_widget("MainWindow", main_window); - return *main_window; + Gtk::Window* main_window = NULL; + _refXml->get_widget("MainWindow", main_window); + return *main_window; } -void +void GuiBuilder::open_file(const std::string& filename) { - // FIXME: to be written. - // Debug line (erase me when done): - std::cout << _("Filename to open: ") << filename << std::endl; + // FIXME: to be written. + // Debug line (erase me when done): + std::cout << _("Filename to open: ") << filename << std::endl; } diff --git a/src/gui_builder.hh b/src/gui_builder.hh index bd6cddd..60fba8b 100644 --- a/src/gui_builder.hh +++ b/src/gui_builder.hh @@ -29,22 +29,23 @@ #include /** \brief This class initialize and starts the whole GUI - -*/ -namespace sgpem { - class GuiBuilder - { - public: - GuiBuilder(const std::string& gladefile = GLADEDIR "/main-window.glade"); - ~GuiBuilder(); - - Gtk::Window& get_initial_window() const; - void open_file(const std::string& filename); - - private: - Glib::RefPtr _refXml; - }; +*/ +namespace sgpem +{ + + class GuiBuilder + { + public: + GuiBuilder(const std::string& gladefile = GLADEDIR "/main-window.glade"); + ~GuiBuilder(); + + Gtk::Window& get_initial_window() const; + void open_file(const std::string& filename); + + private: + Glib::RefPtr _refXml; + }; } //~ namespace sgpem diff --git a/src/main.cc b/src/main.cc index e818f44..da95fa9 100644 --- a/src/main.cc +++ b/src/main.cc @@ -53,6 +53,6 @@ main(int argc, char* argv[]) // Parses options and prepares vector with // filenames of documents to be opened parse_options(argc, argv); - + return 0; } diff --git a/src/parse_opts.cc b/src/parse_opts.cc index e773af7..0ede8db 100644 --- a/src/parse_opts.cc +++ b/src/parse_opts.cc @@ -48,9 +48,9 @@ parse_options(int argc, char** argv) using Glib::OptionGroup; print_license(); - + // Prepare the option entries - + OptionEntry no_gui; OptionEntry policies_dir; OptionEntry modules_dir; @@ -63,99 +63,99 @@ parse_options(int argc, char** argv) no_gui.set_long_name("no-gui"); policies_dir.set_long_name("policies-dir"); modules_dir.set_long_name("modules_dir"); - filename.set_long_name(G_OPTION_REMAINING); + filename.set_long_name(G_OPTION_REMAINING); no_gui.set_description(_("starts the program in command line mode")); policies_dir.set_description(_("adds this directory to the default modules search path")); - modules_dir.set_description(_("adds this directory to default plugin search path")); - filename.set_description(_("a list of savefiles; only the first will be opened")); - + modules_dir.set_description(_("adds this directory to default plugin search path")); + filename.set_description(_("a list of savefiles; only the first will be opened")); + // Places where araguments will be saved bool no_gui_enabled = false; OptionGroup::vecustrings policies_dir_val; OptionGroup::vecustrings modules_dir_val; - OptionGroup::vecstrings fnames; + OptionGroup::vecstrings fnames; - no_gui.set_flags(OptionEntry::FLAG_NO_ARG); - filename.set_flags(OptionEntry::FLAG_FILENAME | OptionEntry::FLAG_OPTIONAL_ARG); + no_gui.set_flags(OptionEntry::FLAG_NO_ARG); + filename.set_flags(OptionEntry::FLAG_FILENAME | OptionEntry::FLAG_OPTIONAL_ARG); // Create the only group - OptionGroup group("options", "options"); + OptionGroup group("options", "options"); group.add_entry(no_gui, no_gui_enabled); group.add_entry(policies_dir, policies_dir_val); group.add_entry(modules_dir, modules_dir_val); - group.add_entry_filename(filename, fnames); + group.add_entry_filename(filename, fnames); - // Create context + // Create context OptionContext context(_("SGPEMv2, a graphical simulator for process " - "scheduling in a multitasking computer")); + "scheduling in a multitasking computer")); context.set_main_group(group); context.set_help_enabled(true); context.set_ignore_unknown_options(false); try - { - // Parse options, initialising the Gtk::Main at the same time - Gtk::Main main_loop(argc, argv, context); - - GlobalPreferences& prefs = GlobalPreferences::get_instance(); - - for(Glib::OptionGroup::vecustrings::const_iterator it = policies_dir_val.begin(); - it != policies_dir_val.end(); ++it) - prefs.add_policies_dir(*it); - - for(Glib::OptionGroup::vecustrings::const_iterator it = modules_dir_val.begin(); - it != modules_dir_val.end(); ++it) - prefs.add_modules_dir(*it); - - - // Now that GlobalPreferences has been initialized properly, - // initialize plugins, too - vector modules = PluginManager::get_instance().get_module_list(); + { + // Parse options, initialising the Gtk::Main at the same time + Gtk::Main main_loop(argc, argv, context); - for(vector::iterator it = modules.begin(); it != modules.end(); ++it) - (*it)->set_enabled(true); + GlobalPreferences& prefs = GlobalPreferences::get_instance(); - vector managers = CPUPoliciesGatekeeper::get_instance().get_registered(); + for (Glib::OptionGroup::vecustrings::const_iterator it = policies_dir_val.begin(); + it != policies_dir_val.end(); ++it) + prefs.add_policies_dir(*it); - for(vector::iterator it = managers.begin(); it != managers.end(); ++it) - (*it)->init(); - - - if(no_gui_enabled) - { - // We don't return to main, instead we - // initialize the command line version - // of sgpemv2 - TextSimulation sim; - std::string str; + for (Glib::OptionGroup::vecustrings::const_iterator it = modules_dir_val.begin(); + it != modules_dir_val.end(); ++it) + prefs.add_modules_dir(*it); - std::cout << std::endl << "% "; - while(getline(std::cin, str)) - { - // Enter main loop - TextSimulation::parse_command(sim, str); - std::cout << std::endl << "% "; - } - } - else - { - GuiBuilder* gui = new GuiBuilder(); - if(fnames.begin() != fnames.end()) - gui->open_file(*fnames.begin()); - main_loop.run(gui->get_initial_window()); - delete gui; - } - } // ~ try - catch(Glib::OptionError e) - { - std::cout << _("Bad invocation: ") << e.what() << std::endl; - std::cout << _("Use the `-?' or `--help' option to see the help") << std::endl; - } -} + // Now that GlobalPreferences has been initialized properly, + // initialize plugins, too + vector modules = PluginManager::get_instance().get_module_list(); + + for (vector::iterator it = modules.begin(); it != modules.end(); ++it) + (*it)->set_enabled(true); + + vector managers = CPUPoliciesGatekeeper::get_instance().get_registered(); + + for (vector::iterator it = managers.begin(); it != managers.end(); ++it) + (*it)->init(); + + + if (no_gui_enabled) + { + // We don't return to main, instead we + // initialize the command line version + // of sgpemv2 + TextSimulation sim; + std::string str; + + std::cout << std::endl << "% "; + while (getline(std::cin, str)) + { + // Enter main loop + TextSimulation::parse_command(sim, str); + std::cout << std::endl << "% "; + } + } + else + { + GuiBuilder* gui = new GuiBuilder(); + if (fnames.begin() != fnames.end()) + gui->open_file(*fnames.begin()); + main_loop.run(gui->get_initial_window()); + delete gui; + } + + } // ~ try + catch (Glib::OptionError e) + { + std::cout << _("Bad invocation: ") << e.what() << std::endl; + std::cout << _("Use the `-?' or `--help' option to see the help") << std::endl; + } +} void diff --git a/src/parse_opts.hh b/src/parse_opts.hh index 1abd3ac..e2f2eb0 100644 --- a/src/parse_opts.hh +++ b/src/parse_opts.hh @@ -23,8 +23,8 @@ /** \brief Parses command line options * - * Parses command line options and sets argv to the first filename - * given to the cmdline. + * Parses command line options and sets argv to the first filename + * given to the cmdline. * If no filename is given, in the end argc will be 0. * * Else argc will contain the length of the remaining argv[]. diff --git a/src/schedulables_widget.cc b/src/schedulables_widget.cc index 3d8de68..e1c5358 100644 --- a/src/schedulables_widget.cc +++ b/src/schedulables_widget.cc @@ -28,14 +28,12 @@ using namespace sgpem; SchedulablesWidget::SchedulablesWidget() - : Glib::ObjectBase("sgpem_SchedulablesWidget"), CairoWidget() -{ -} - + : Glib::ObjectBase("sgpem_SchedulablesWidget"), CairoWidget() +{} + SchedulablesWidget::~SchedulablesWidget() -{ -} +{} void @@ -49,7 +47,7 @@ SchedulablesWidget::draw_widget(cairo_t* ctx) Color red = { 1, 0, 0 }; Point center = { 25, 25 }; - + ce.draw_3dsphere(center, 20, red); } diff --git a/src/templates/deletor.tcc b/src/templates/deletor.tcc index d1b1b7d..db178f8 100644 --- a/src/templates/deletor.tcc +++ b/src/templates/deletor.tcc @@ -27,11 +27,11 @@ namespace memory { - template - struct deletor : public std::unary_function - { - inline void operator()(T* o) { delete o; } - }; + template + struct deletor : public std::unary_function + { + inline void operator()(T* o) { delete o; } + }; } //~ namespace memory diff --git a/src/templates/singleton.hh b/src/templates/singleton.hh index 4053645..3b5a286 100644 --- a/src/templates/singleton.hh +++ b/src/templates/singleton.hh @@ -44,7 +44,7 @@ namespace sgpem * \return The instantiated object */ static Instantiated_class& get_instance(); - + protected: static Glib::RecMutex SG_DLLLOCAL _mutex; diff --git a/src/templates/singleton.tcc b/src/templates/singleton.tcc index b5d30e7..44386e8 100644 --- a/src/templates/singleton.tcc +++ b/src/templates/singleton.tcc @@ -34,8 +34,8 @@ template Instantiated_class& sgpem::Singleton::get_instance() { - Glib::RecMutex::Lock lock(_mutex); - if(_instance == NULL) + Glib::RecMutex::Lock lock (_mutex); + if (_instance == NULL) _instance = new Instantiated_class(); return *_instance; } diff --git a/src/templates/smartp.tcc b/src/templates/smartp.tcc index 6c3178a..7abfa9b 100644 --- a/src/templates/smartp.tcc +++ b/src/templates/smartp.tcc @@ -47,9 +47,9 @@ namespace memory template smart_ptr::~smart_ptr() throw() { - if(--(_contents->rc) == 0) + if (--(_contents->rc) == 0) { - if(_contents->ptr != 0) + if (_contents->ptr != 0) !isArray ? delete _contents->ptr : delete [] _contents->ptr; delete _contents; } @@ -61,11 +61,11 @@ namespace memory smart_ptr& smart_ptr::operator=(const smart_ptr& sptr) throw() { - if(this != &sptr && _contents != sptr._contents) + if (this != &sptr && _contents != sptr._contents) { - if(--(_contents->rc) == 0) + if (--(_contents->rc) == 0) { - if(_contents->ptr != 0) + if (_contents->ptr != 0) !isArray ? delete _contents->ptr : delete [] _contents->ptr; delete _contents; } @@ -165,11 +165,11 @@ namespace memory smart_ptr::smart_ptr(const smart_ptr& sptr) throw(std::bad_cast) { - if(!sptr._contents->ptr || dynamic_cast(sptr._contents->ptr) == 0) + if (!sptr._contents->ptr || dynamic_cast(sptr._contents->ptr) == 0) throw std::bad_cast(); // I know, I know... this is Evil(TM): - _contents = reinterpret_cast::contents_type*>(sptr._contents); + _contents = reinterpret_cast::contents_type* > (sptr._contents); (_contents->rc)++; } diff --git a/src/testsuite/stubs/history.cc b/src/testsuite/stubs/history.cc index 4f5be31..7e1f84a 100644 --- a/src/testsuite/stubs/history.cc +++ b/src/testsuite/stubs/history.cc @@ -24,90 +24,90 @@ using namespace sgpem; - memory::smart_ptr - History::get_scheduled_at(int time) const - { - using namespace memory; - smart_ptr scheduled_at = smart_ptr(); - if (0 <= time && time <= _total_time_elapsed) - { - smart_ptr sl = get_simulation_status_at(time); - bool found = false; - bool invalid = sl == smart_ptr(); - for (uint i = 0; !found && !invalid && i < sl->size(); i++) - { - const DynamicSchedulable* ss = sl->get_item_at(i); - if ((bool)ss && ss->get_state() == DynamicSchedulable::state_running) - { - scheduled_at = smart_ptr(new DynamicSchedulable(*(ss))); - found = true; - } - } - } - return scheduled_at; - } +memory::smart_ptr +History::get_scheduled_at(int time) const +{ + using namespace memory; + smart_ptr scheduled_at = smart_ptr(); + if (0 <= time && time <= _total_time_elapsed) + { + smart_ptr sl = get_simulation_status_at(time); + bool found = false; + bool invalid = sl == smart_ptr(); + for (uint i = 0; !found && !invalid && i < sl->size(); i++) + { + const DynamicSchedulable* ss = sl->get_item_at(i); + if ((bool)ss && ss->get_state() == DynamicSchedulable::state_running) + { + scheduled_at = smart_ptr(new DynamicSchedulable(*(ss))); + found = true; + } + } + } + return scheduled_at; +} - memory::smart_ptr - History::get_simulation_status_at(int time) const - { - using namespace memory; - smart_ptr simulation_status_at = smart_ptr(); - if (0 <= time && time <= _total_time_elapsed) - { - if (_slice == memory::smart_ptr()) - std::cout<<"History::get_simulation_status_at.NULL.error"; - else - simulation_status_at = memory::smart_ptr - ( - new ReadyQueue - ( - *(_slice->get_simulation_status()) - ) - ); - } - return simulation_status_at; - } +memory::smart_ptr +History::get_simulation_status_at(int time) const +{ + using namespace memory; + smart_ptr simulation_status_at = smart_ptr(); + if (0 <= time && time <= _total_time_elapsed) + { + if (_slice == memory::smart_ptr()) + std::cout << "History::get_simulation_status_at.NULL.error"; + else + simulation_status_at = memory::smart_ptr + ( + new ReadyQueue + ( + *(_slice->get_simulation_status()) + ) + ); + } + return simulation_status_at; +} - int - History::get_current_time() const - { - return _total_time_elapsed; - } +int +History::get_current_time() const +{ + return _total_time_elapsed; +} - void - History::enqueue_slice(const sgpem::ReadyQueue& status) - { - _slice = memory::smart_ptr(new Slice(_total_time_elapsed, 1, status)); - _total_time_elapsed++; - } +void +History::enqueue_slice(const sgpem::ReadyQueue& status) +{ + _slice = memory::smart_ptr(new Slice(_total_time_elapsed, 1, status)); + _total_time_elapsed++; +} - void - History::truncate_at(int instant) - { - //std::cout << "\nRecreating a Singleton History"; - _slice = memory::smart_ptr(); - _total_time_elapsed = -1; - } +void +History::truncate_at(int instant) +{ + //std::cout << "\nRecreating a Singleton History"; + _slice = memory::smart_ptr(); + _total_time_elapsed = -1; +} - History& - History::get_instance() - { - if (History::_instance == NULL) - History::_instance = new History(); - return *History::_instance; - } +History& +History::get_instance() +{ + if (History::_instance == NULL) + History::_instance = new History(); + return *History::_instance; +} - History::History() - { - _slice = memory::smart_ptr(); - _total_time_elapsed = -1; - } +History::History() +{ + _slice = memory::smart_ptr(); + _total_time_elapsed = -1; +} - History * History::_instance = NULL; +History * History::_instance = NULL; diff --git a/src/testsuite/stubs/history.hh b/src/testsuite/stubs/history.hh index 4ce1251..bc9779c 100644 --- a/src/testsuite/stubs/history.hh +++ b/src/testsuite/stubs/history.hh @@ -52,58 +52,58 @@ namespace sgpem { - /** an History stub, should only save the last state included. + /** an History stub, should only save the last state included. + */ + class History : public ObservedSubject + { + + public: + + + /** Returns the DynamicSchedulable of the schedulable + * which was running at the time, if any. */ - class History : public ObservedSubject - { - - public: + memory::smart_ptr + get_scheduled_at(int time) const; - /** Returns the DynamicSchedulable of the schedulable - * which was running at the time, if any. - */ - memory::smart_ptr - get_scheduled_at(int time) const; + /** Returns the last recorded instant, but may raise an error. + */ + memory::smart_ptr + get_simulation_status_at(int time) const; - /** Returns the last recorded instant, but may raise an error. - */ - memory::smart_ptr - get_simulation_status_at(int time) const; + /** Returns the total time recorded. + */ + int + get_current_time() const; - /** Returns the total time recorded. - */ - int - get_current_time() const; + /** Extends the recorded history by one unit, overwriting the old value + */ + void + enqueue_slice(const sgpem::ReadyQueue& status); - /** Extends the recorded history by one unit, overwriting the old value - */ - void - enqueue_slice(const sgpem::ReadyQueue& status); + /** STUB: THIS FEATURE IS NOT AVAILABLE + */ + void + truncate_at(int instant); - /** STUB: THIS FEATURE IS NOT AVAILABLE - */ - void - truncate_at(int instant); + /** Returns the singleton instance. + */ + static History& + get_instance(); - /** Returns the singleton instance. - */ - static History& - get_instance(); + private: + History(); - - private: - History(); - - static History * _instance; - int _total_time_elapsed; - memory::smart_ptr _slice; - }; + static History * _instance; + int _total_time_elapsed; + memory::smart_ptr _slice; + }; } //~ namespace sgpem diff --git a/src/testsuite/stubs/policy_manager.cc b/src/testsuite/stubs/policy_manager.cc index db5dca2..26ecda0 100644 --- a/src/testsuite/stubs/policy_manager.cc +++ b/src/testsuite/stubs/policy_manager.cc @@ -28,24 +28,24 @@ PolicyManager::PolicyManager() PolicyManager& PolicyManager::get_registered_manager() { - if (_registered == NULL) - _registered = new PolicyManager(); - return *_registered; + if (_registered == NULL) + _registered = new PolicyManager(); + return *_registered; } - Policy& +Policy& PolicyManager::get_policy() { - return PRRPolicy::get_instance(); + return PRRPolicy::get_instance(); } - void +void PolicyManager::init() {} - PolicyManager::~PolicyManager() +PolicyManager::~PolicyManager() { - if(_registered == this) _registered = NULL; + if (_registered == this) _registered = NULL; } diff --git a/src/testsuite/stubs/policy_manager.hh b/src/testsuite/stubs/policy_manager.hh index 043b7b7..8c4060a 100644 --- a/src/testsuite/stubs/policy_manager.hh +++ b/src/testsuite/stubs/policy_manager.hh @@ -45,29 +45,29 @@ namespace sgpem { - /** A policyManager stub, provides access to the PRRPolicy. - */ - class PolicyManager - { - public: + /** A policyManager stub, provides access to the PRRPolicy. + */ + class PolicyManager + { + public: - PolicyManager(); + PolicyManager(); - static PolicyManager& - get_registered_manager(); + static PolicyManager& + get_registered_manager(); - virtual Policy& - get_policy(); + virtual Policy& + get_policy(); - virtual void - init(); + virtual void + init(); - virtual - ~PolicyManager(); + virtual + ~PolicyManager(); - private: - static PolicyManager* _registered; - }; + private: + static PolicyManager* _registered; + }; } #endif diff --git a/src/testsuite/stubs/prrpolicy.cc b/src/testsuite/stubs/prrpolicy.cc index 8c0ea72..157d204 100644 --- a/src/testsuite/stubs/prrpolicy.cc +++ b/src/testsuite/stubs/prrpolicy.cc @@ -24,97 +24,97 @@ using namespace sgpem; PRRPolicy::PRRPolicy() { - _instance = this; + _instance = this; } PRRPolicy::PRRPolicy(int quantum) : _quantum(quantum) { - _instance = this; + _instance = this; } Policy& PRRPolicy::get_instance() { - if(_instance == NULL) _instance = new PRRPolicy(3); // quantum size - return *_instance; + if (_instance == NULL) _instance = new PRRPolicy(3); // quantum size + return *_instance; } PRRPolicy::~PRRPolicy() {} - void +void PRRPolicy::configure() - throw(UserInterruptException) +throw(UserInterruptException) {} - void +void PRRPolicy::sort_queue() const - throw(UserInterruptException) +throw(UserInterruptException) { - ReadyQueue* local_sl = Scheduler::get_instance().get_ready_queue(); - for (uint useless = 0; useless < local_sl->size(); useless++) - for (uint i = 0; i < local_sl->size() - 1; i++) - if - ( - local_sl->get_item_at(i)->get_schedulable()->get_priority() > - local_sl->get_item_at(i + 1)->get_schedulable()->get_priority() - ) - local_sl->swap(i, i + 1); + ReadyQueue* local_sl = Scheduler::get_instance().get_ready_queue(); + for (uint useless = 0; useless < local_sl->size(); useless++) + for (uint i = 0; i < local_sl->size() - 1; i++) + if + ( + local_sl->get_item_at(i)->get_schedulable()->get_priority() > + local_sl->get_item_at(i + 1)->get_schedulable()->get_priority() + ) + local_sl->swap(i, i + 1); } - void +void PRRPolicy::activate() {} - void +void PRRPolicy::deactivate() {} - int +int PRRPolicy::get_id() const { - return 42; + return 42; } - sgpem::policy_sorts_type +sgpem::policy_sorts_type PRRPolicy::wants() const - throw(UserInterruptException) +throw(UserInterruptException) { - return policy_sorts_processes; + return policy_sorts_processes; } - Glib::ustring +Glib::ustring PRRPolicy::get_name() const { - return "42"; + return "42"; } - Glib::ustring +Glib::ustring PRRPolicy::get_description() const { - return "42"; + return "42"; } - bool +bool PRRPolicy::is_pre_emptive() const - throw(UserInterruptException) +throw(UserInterruptException) { - return 1; + return 1; } - int +int PRRPolicy::get_time_slice() const - throw(UserInterruptException) +throw(UserInterruptException) { - return _quantum; + return _quantum; } - PolicyParameters& +PolicyParameters& PRRPolicy::get_parameters() { - return _parameters; + return _parameters; } Policy* diff --git a/src/testsuite/stubs/prrpolicy.hh b/src/testsuite/stubs/prrpolicy.hh index 6875874..3f718a9 100644 --- a/src/testsuite/stubs/prrpolicy.hh +++ b/src/testsuite/stubs/prrpolicy.hh @@ -48,81 +48,81 @@ namespace sgpem { - /** An hard-coded Priority Round Robin policy - * It's actually called PRRPolicy, altough my personal taste would have suggested - * naming it - * Prioriy-Reliant Roughly-Realized Recently-Reimplemented Round-Robin Policy, - * i.e. PRRRRRRR-Policy. - * it adds a new constructor taking the quantum size (time slice) - */ - class PRRPolicy : public Policy - { - public: + /** An hard-coded Priority Round Robin policy + * It's actually called PRRPolicy, altough my personal taste would have suggested + * naming it + * Prioriy-Reliant Roughly-Realized Recently-Reimplemented Round-Robin Policy, + * i.e. PRRRRRRR-Policy. + * it adds a new constructor taking the quantum size (time slice) + */ + class PRRPolicy : public Policy + { + public: - PRRPolicy(); + PRRPolicy(); - PRRPolicy(int quantum); + PRRPolicy(int quantum); - static Policy& - get_instance(); - - virtual - ~PRRPolicy(); + static Policy& + get_instance(); - virtual void - configure() - throw(UserInterruptException); + virtual + ~PRRPolicy(); - virtual void - sort_queue() const - throw(UserInterruptException); + virtual void + configure() + throw(UserInterruptException); + + virtual void + sort_queue() const + throw(UserInterruptException); - virtual void - activate(); + virtual void + activate(); - virtual void - deactivate(); - - - virtual int - get_id() const; - - virtual sgpem::policy_sorts_type - wants() const - throw(UserInterruptException); - - - virtual Glib::ustring - get_name() const; - - virtual Glib::ustring - get_description() const; - - virtual bool - is_pre_emptive() const - throw(UserInterruptException); - - virtual int - get_time_slice() const - throw(UserInterruptException); + virtual void + deactivate(); - virtual PolicyParameters& - get_parameters(); + virtual int + get_id() const; + + virtual sgpem::policy_sorts_type + wants() const + throw(UserInterruptException); + + + virtual Glib::ustring + get_name() const; + + virtual Glib::ustring + get_description() const; + + virtual bool + is_pre_emptive() const + throw(UserInterruptException); + + virtual int + get_time_slice() const + throw(UserInterruptException); + + + virtual PolicyParameters& + get_parameters(); - protected: + protected: - PolicyParameters _parameters; - int _id; - int _quantum; + PolicyParameters _parameters; + int _id; + int _quantum; - private: + private: - static Policy* _instance; - }; + static Policy* _instance; + }; } diff --git a/src/testsuite/test-global_preferences_serialization.cc b/src/testsuite/test-global_preferences_serialization.cc index bdc79fc..ac57cee 100644 --- a/src/testsuite/test-global_preferences_serialization.cc +++ b/src/testsuite/test-global_preferences_serialization.cc @@ -32,33 +32,34 @@ // from here and further until the bottom, all to throw away I suppose int -main(int argc, char** argv) { - +main(int argc, char** argv) +{ + using namespace sgpem; using Glib::ustring; using std::cout; using std::endl; using std::ostringstream; - + GlobalPreferences& gp = GlobalPreferences::get_instance(); - if(argc<2) + if (argc < 2) { cout << "GlobalPreferences serialization test program" << endl; cout << "Syntax: test-global_preferences_serialization [mod1 mod2 ...][% pol1 pol2 ...]" << endl << endl; cout << "This test add modules directories (mod1 mod2 ...) and modules directories (mod1 mod2 ...)" << endl - << "to GlobalPreferences, write it to the configuration file " << gp.get_config_filename() - << ", read it and compare with saved one." << endl << endl; + << "to GlobalPreferences, write it to the configuration file " << gp.get_config_filename() + << ", read it and compare with saved one." << endl << endl; } - int i=1; - while(i threads = p.get_threads(); - for(unsigned int j = 0; j < threads.size(); ++j) + for (unsigned int j = 0; j < threads.size(); ++j) { - DynamicThread& t = (DynamicThread&)*threads[j]; - if(t == thread) - return t; + DynamicThread& t = (DynamicThread&) * threads[j]; + if (t == thread) + return t; } } @@ -117,18 +117,18 @@ find_thread(const ConcreteEnvironment& env, const Thread& _thread) { const DynamicThread& thread = (DynamicThread&)_thread; const Environment::Processes& processes = env.get_processes(); - + // please forgive me, I'm sick of using iterators... - for(unsigned int i = 0; i < processes.size(); ++i) + for (unsigned int i = 0; i < processes.size(); ++i) { const Process& p = *processes[i]; vector threads = p.get_threads(); - for(unsigned int j = 0; j < threads.size(); ++j) + for (unsigned int j = 0; j < threads.size(); ++j) { - const DynamicThread& t = (const DynamicThread&)*threads[j]; - if(t == thread) - return t; + const DynamicThread& t = (const DynamicThread&) * threads[j]; + if (t == thread) + return t; } } @@ -140,7 +140,7 @@ main(int argc, char** argv) { ostream& info = cout; ostream& test = cerr; - + using namespace sgpem; ConcreteHistory h; @@ -148,20 +148,20 @@ main(int argc, char** argv) info << "Created the ConcreteHistory instance\n"; test << "Checking if it contains only one Environment... "; - - if(h.get_size() == 1) + + if (h.get_size() == 1) test << "PASS"; else test << "FAIL"; test << endl; - + const ConcreteEnvironment& environment = h.get_last_environment(); info << "Obtained the only contained environment\n"; test << "Checking if the environment is empty... "; - if(environment.get_processes().size() == 0 && + if (environment.get_processes().size() == 0 && environment.get_resources().size() == 0 && environment.get_sorted_queue().size() == 0) test << "PASS"; @@ -172,101 +172,101 @@ main(int argc, char** argv) DummyObserver observer; info << "Created the observer\n"; - + h.attach(observer); info << "Attached to the history\n"; - const ProcessCreationData processes[2] = - { - { "p1", 0, 3 }, - { "p2", 3, 1 } - }; + const ProcessCreationData processes[2] = + { + { "p1", 0, 3 }, + { "p2", 3, 1 } + }; - DynamicProcess& p1 = h.add_process(processes[0].name, - processes[0].arrival_time, - processes[0].base_priority); + DynamicProcess& p1 = h.add_process(processes[0].name, + processes[0].arrival_time, + processes[0].base_priority); - DynamicProcess& p2 = h.add_process(processes[1].name, - processes[1].arrival_time, - processes[1].base_priority); + DynamicProcess& p2 = h.add_process(processes[1].name, + processes[1].arrival_time, + processes[1].base_priority); - const ThreadCreationData threads[4] = - { - { "p2_1", &p2, 3, 0, 0 }, - { "p1_1", &p1, 2, 0, 2 }, - { "p1_2", &p1, 1, 1, 0 }, - { "p2_2", &p2, 5, 3, 1 } - }; + const ThreadCreationData threads[4] = + { + { "p2_1", &p2, 3, 0, 0 }, + { "p1_1", &p1, 2, 0, 2 }, + { "p1_2", &p1, 1, 1, 0 }, + { "p2_2", &p2, 5, 3, 1 } + }; DynamicThread& p2_1 = h.add_thread(threads[0].name, - *threads[0].parent, - threads[0].cpu_time, - threads[0].arrival_time, - threads[0].base_priority); + *threads[0].parent, + threads[0].cpu_time, + threads[0].arrival_time, + threads[0].base_priority); DynamicThread& p1_1 = h.add_thread(threads[1].name, - *threads[1].parent, - threads[1].cpu_time, - threads[1].arrival_time, - threads[1].base_priority); + *threads[1].parent, + threads[1].cpu_time, + threads[1].arrival_time, + threads[1].base_priority); DynamicThread& p1_2 = h.add_thread(threads[2].name, - *threads[2].parent, - threads[2].cpu_time, - threads[2].arrival_time, - threads[2].base_priority); - - DynamicThread& p2_2 = h.add_thread(threads[3].name, - *threads[3].parent, - threads[3].cpu_time, - threads[3].arrival_time, - threads[3].base_priority); + *threads[2].parent, + threads[2].cpu_time, + threads[2].arrival_time, + threads[2].base_priority); - const ResourceCreationData resources[2] = - { - { "res1", true, 2, 0 }, - { "res2", false, 1, 0 } - }; + DynamicThread& p2_2 = h.add_thread(threads[3].name, + *threads[3].parent, + threads[3].cpu_time, + threads[3].arrival_time, + threads[3].base_priority); + + const ResourceCreationData resources[2] = + { + { "res1", true, 2, 0 }, + { "res2", false, 1, 0 } + }; const History::ResourcePair res1 = h.add_resource(resources[0].name, - resources[0].preemptable, - resources[0].places, - resources[0].availability); - - const History::ResourcePair res2 = h.add_resource(resources[1].name, - resources[1].preemptable, - resources[1].places, - resources[1].availability); + resources[0].preemptable, + resources[0].places, + resources[0].availability); - const RequestCreationData requests[2] = - { - { &p1_2, 0 }, - { &p2_1, 1 } - }; + const History::ResourcePair res2 = h.add_resource(resources[1].name, + resources[1].preemptable, + resources[1].places, + resources[1].availability); + + const RequestCreationData requests[2] = + { + { &p1_2, 0 }, + { &p2_1, 1 } + }; DynamicRequest& req1 = h.add_request(*requests[0].owner, requests[0].instant); DynamicRequest& req2 = h.add_request(*requests[1].owner, requests[1].instant); - const SubRequestCreationData subrequests[3] = - { - { &req1, res1.first, 1 }, - { &req2, res2.first, 2 }, - { &req2, res1.first, 1 } - }; + const SubRequestCreationData subrequests[3] = + { + { &req1, res1.first, 1 }, + { &req2, res2.first, 2 }, + { &req2, res1.first, 1 } + }; const DynamicSubRequest& sreq1 = h.add_subrequest(*subrequests[0].request, - subrequests[0].resource_key, - subrequests[0].duration); - + subrequests[0].resource_key, + subrequests[0].duration); + const DynamicSubRequest& sreq2 = h.add_subrequest(*subrequests[1].request, - subrequests[1].resource_key, - subrequests[1].duration); - + subrequests[1].resource_key, + subrequests[1].duration); + const DynamicSubRequest& sreq3 = h.add_subrequest(*subrequests[2].request, - subrequests[2].resource_key, - subrequests[2].duration); + subrequests[2].resource_key, + subrequests[2].duration); info << "Done adding required data by using the History factory interface\n"; @@ -275,7 +275,7 @@ main(int argc, char** argv) // const Environment::SubRequestQueue res2_queue = environment.get_request_queue(res2.first); test << "Checking if the environment contains the correct request queues... "; - + typedef Environment::SubRequestQueue::const_iterator ReqIterator; // ************* FIXME *************** : @@ -286,15 +286,15 @@ main(int argc, char** argv) // bool res1_req2_match = false; // bool res2_req1_match = false; // bool bad_match = false; - + // for(ReqIterator it = res1_queue.begin(); it != res1_queue.end(); ++it) // { // if(!res1_req1_match && *it == &req1) -// res1_req1_match = true; +// res1_req1_match = true; // else if(!res1_req2_match && *it == &req2) -// res1_req2_match == true; +// res1_req2_match == true; // else -// bad_match = true; +// bad_match = true; // } // if(!res2_req1_match && *res2_queue.begin() == &req1) @@ -309,25 +309,25 @@ main(int argc, char** argv) // } // else // test << "FAIL"; - test << endl; + test << endl; - - ConcreteEnvironment* environment1 = new ConcreteEnvironment(environment); - ConcreteEnvironment* environment2 = new ConcreteEnvironment(environment); - ConcreteEnvironment* environment3 = new ConcreteEnvironment(environment); - ConcreteEnvironment* environment4 = new ConcreteEnvironment(environment); - ConcreteEnvironment* environment5 = new ConcreteEnvironment(environment); + + ConcreteEnvironment* environment1 = new ConcreteEnvironment(environment); + ConcreteEnvironment* environment2 = new ConcreteEnvironment(environment); + ConcreteEnvironment* environment3 = new ConcreteEnvironment(environment); + ConcreteEnvironment* environment4 = new ConcreteEnvironment(environment); + ConcreteEnvironment* environment5 = new ConcreteEnvironment(environment); info << "Created 5 copies of inital environment\n"; const History::prio_t priorities[5] = { 3, 1, 4, 5, 2 }; - + find_thread(*environment1, p1_1).set_priority_push(priorities[0]); find_thread(*environment2, p1_1).set_priority_push(priorities[1]); find_thread(*environment3, p1_1).set_priority_push(priorities[2]); find_thread(*environment4, p1_1).set_priority_push(priorities[3]); find_thread(*environment5, p1_1).set_priority_push(priorities[4]); - + info << "Updated dynamic priority of threads\n"; h.append_new_environment(environment1); @@ -340,7 +340,7 @@ main(int argc, char** argv) test << "Checking if history size is 6... "; - if(h.get_size() == 6) + if (h.get_size() == 6) test << "PASS"; else test << "FAIL"; @@ -351,7 +351,7 @@ main(int argc, char** argv) test << "Checking if dynamic priority of thread at instant 1 and 5 is different... "; - if(t1.get_priority_push() != t5.get_priority_push()) + if (t1.get_priority_push() != t5.get_priority_push()) test << "PASS"; else test << "FAIL"; @@ -361,10 +361,10 @@ main(int argc, char** argv) test << "Checking if dynamic priority of thread at instant 4, is different "; test << "from that at instant 1 and 5, and equal to the one expected... "; - - if(t4.get_priority_push() != t1.get_priority_push() && - t4.get_priority_push() != t5.get_priority_push() && - t4.get_priority_push() == priorities[3]) + + if (t4.get_priority_push() != t1.get_priority_push() && + t4.get_priority_push() != t5.get_priority_push() && + t4.get_priority_push() == priorities[3]) test << "PASS"; else test << "FAIL"; @@ -372,55 +372,55 @@ main(int argc, char** argv) test << "Checking whether all subrequests in the last environment "; test << "refer to valid resources... "; - + const ConcreteEnvironment& last_env = h.get_last_environment(); const Environment::Processes& le_processes = last_env.get_processes(); const Environment::Resources& le_resources = last_env.get_resources(); - + bool subreq_pass = true; - - for(unsigned int i = 0; i < le_processes.size(); ++i) + + for (unsigned int i = 0; i < le_processes.size(); ++i) { vector threads = le_processes[i]->get_threads(); - for(unsigned int j = 0; j < threads.size(); ++j) + for (unsigned int j = 0; j < threads.size(); ++j) { vector requests = threads[j]->get_requests(); - for(unsigned int k = 0; k < requests.size(); ++k) + for (unsigned int k = 0; k < requests.size(); ++k) { - vector subrequests = requests[k]->get_subrequests(); + vector subrequests = requests[k]->get_subrequests(); - for(unsigned int x = 0; x < subrequests.size(); ++x) - { - if(le_resources.find(subrequests[x]->get_resource_key()) == le_resources.end()) - subreq_pass = false; - } + for (unsigned int x = 0; x < subrequests.size(); ++x) + { + if (le_resources.find(subrequests[x]->get_resource_key()) == le_resources.end()) + subreq_pass = false; + } } } } - if(subreq_pass) + if (subreq_pass) test << "PASS"; else test << "FAIL"; test << endl; test << "Checking if history throws an exception on accessing a nonexistent environment... "; - + try { h.get_environment_at(6); test << "FAIL"; } - catch(out_of_range) + catch (out_of_range) { test << "PASS"; } test << endl; ThreadCreationData p1_3_d = { "p1_3", &p1, 3, 4, 0 }; - + Thread& p1_3 = h.add_thread(p1_3_d.name, *p1_3_d.parent, p1_3_d.cpu_time, @@ -431,7 +431,7 @@ main(int argc, char** argv) test << "Checking if history has size 1 after adding a thread... "; - if(h.get_size() == 1) + if (h.get_size() == 1) test << "PASS"; else test << "FAIL"; @@ -442,12 +442,12 @@ main(int argc, char** argv) h.append_new_environment(environment6); info << "Added a new environment to the history as a clear-cut copy of the last" << endl; - + h.remove(res1.first); test << "Checking if history has size 1 after removing a resource... "; - if(h.get_size() == 1) + if (h.get_size() == 1) test << "PASS"; else test << "FAIL"; @@ -456,7 +456,7 @@ main(int argc, char** argv) test << "Checking whether objects inside the history are the same as the beginning, "; test << "except for the missing thread and associated requests... "; - + const Environment::Processes& final_processes = h.get_last_environment().get_processes(); const Environment::Resources& final_resources = h.get_last_environment().get_resources(); @@ -464,57 +464,57 @@ main(int argc, char** argv) bool final_p2_match = false; bool final_bad_match = false; bool final_sreq2_match = false; - - for(unsigned int i = 0; i < final_processes.size(); ++i) - { - DynamicProcess& p = (DynamicProcess&)*final_processes[i]; - if(!final_p1_match && p == p1) + for (unsigned int i = 0; i < final_processes.size(); ++i) + { + DynamicProcess& p = (DynamicProcess&) * final_processes[i]; + + if (!final_p1_match && p == p1) final_p1_match = true; - else if(!final_p2_match && p == p2) + else if (!final_p2_match && p == p2) final_p2_match = true; else final_bad_match = true; vector& threads = p.get_dynamic_threads(); - for(unsigned int j = 0; j < threads.size(); ++j) + for (unsigned int j = 0; j < threads.size(); ++j) { vector requests = threads[j]->get_dynamic_requests(); - for(unsigned int k = 0; k < requests.size(); ++k) + for (unsigned int k = 0; k < requests.size(); ++k) { - vector subrequests = requests[k]->get_dynamic_subrequests(); + vector subrequests = requests[k]->get_dynamic_subrequests(); - for(unsigned int x = 0; x < subrequests.size(); ++x) - { - // NOTE this will of course fail if the subrequests which should not be here - // are still in the environment - if(!final_sreq2_match && *subrequests[x] == sreq2) - final_sreq2_match = true; - else - final_bad_match = true; - } + for (unsigned int x = 0; x < subrequests.size(); ++x) + { + // NOTE this will of course fail if the subrequests which should not be here + // are still in the environment + if (!final_sreq2_match && *subrequests[x] == sreq2) + final_sreq2_match = true; + else + final_bad_match = true; + } } } } typedef Environment::Resources::const_iterator ResourceIt; - if(final_resources.size() == 1) + if (final_resources.size() == 1) { - DynamicResource& r = (DynamicResource&)*(final_resources.begin()->second); - if(!(r == *res2.second)) + DynamicResource& r = (DynamicResource&) * (final_resources.begin()->second); + if (!(r == *res2.second)) final_bad_match = true; } else final_bad_match = true; - if(!final_bad_match && final_p1_match && final_p2_match && final_sreq2_match) + if (!final_bad_match && final_p1_match && final_p2_match && final_sreq2_match) test << "PASS"; else test << "FAIL"; - test << endl; + test << endl; test << "Checking whether ConcreteHistory throws an exception if we try to use "; @@ -523,12 +523,12 @@ main(int argc, char** argv) try { // FIXME This causes a warning because we force a conversion of a negative number - // to an unsigned integer. What did the designers wanted to test by doing this? + // to an unsigned integer. What did the designers wanted to test by doing this? // The compiler? h.get_environment_at(-17); test << "FAIL"; } - catch(out_of_range) + catch (out_of_range) { test << "PASS"; } @@ -536,7 +536,7 @@ main(int argc, char** argv) test << "Internal observer's counter should be 21... "; - if(observer._i == 21) + if (observer._i == 21) test << "PASS"; else test << "FAIL"; diff --git a/src/testsuite/test-key_file.cc b/src/testsuite/test-key_file.cc index 6c31b97..a2af170 100644 --- a/src/testsuite/test-key_file.cc +++ b/src/testsuite/test-key_file.cc @@ -31,68 +31,69 @@ // from here and further until the bottom, all to throw away I suppose int -main(int argc, char** argv) { - +main(int argc, char** argv) +{ + using namespace sgpem; using Glib::ustring; using std::cout; using std::endl; - - if((argc<4) || (argc%2)!=0) + + if ((argc < 4) || (argc % 2) != 0) { cout << "KeyFile class test program" << endl; cout << "Syntax: test-key_file filename key1 value1 [key2 value2...]" << endl; - cout << "total number of parameters must be odd." - << endl << endl; - cout << "This test create a KeyFile object, fill it with all key/value pairs," << endl - << "write it to the file \"filename\", read it into a new KeyFile object" << endl - << "and compare all readed values against original values." << endl << endl - << "If all key/values match the program print \"Test was successful\" and return 0." << endl - << "If some key/values doesn't match the program print \"Test failed\" and return 1." - << endl << endl; - cout << "If there isn't any parameter or bad number of parameters return 2." - << endl << endl; - cout << "NOTE: 1) Test fails with invalid filenames or duplicated key in input." - << endl; - cout << " 2) File \"filename\" remains in current directory after test execution." - << endl << endl; + cout << "total number of parameters must be odd." + << endl << endl; + cout << "This test create a KeyFile object, fill it with all key/value pairs," << endl + << "write it to the file \"filename\", read it into a new KeyFile object" << endl + << "and compare all readed values against original values." << endl << endl + << "If all key/values match the program print \"Test was successful\" and return 0." << endl + << "If some key/values doesn't match the program print \"Test failed\" and return 1." + << endl << endl; + cout << "If there isn't any parameter or bad number of parameters return 2." + << endl << endl; + cout << "NOTE: 1) Test fails with invalid filenames or duplicated key in input." + << endl; + cout << " 2) File \"filename\" remains in current directory after test execution." + << endl << endl; return 2; } KeyFile kfile; KeyFile kfile_bis; - - // fill KeyFile object - for(int index = 2; index& pparam); - + ustring description; T low_bound; T up_bound; @@ -70,40 +70,36 @@ namespace sgpem template CommandParameter::CommandParameter(const ustring& _description, - const T& _low_bound, - const T& _up_bound, - bool _required, - const T& _preset) : - description(_description), low_bound(_low_bound), - up_bound(_up_bound), required(_required), preset(_preset), - value(_preset) - { - } + const T& _low_bound, + const T& _up_bound, + bool _required, + const T& _preset) : + description(_description), low_bound(_low_bound), + up_bound(_up_bound), required(_required), preset(_preset), + value(_preset) + {} template CommandParameter::CommandParameter(const PolicyParameters::Parameter& pparam) : - description(pparam.get_name()), - low_bound(pparam.get_lower_bound()), - up_bound(pparam.get_upper_bound()), required(pparam.is_required()), - preset(pparam.get_default()), value(pparam.get_value()) - { - } + description(pparam.get_name()), + low_bound(pparam.get_lower_bound()), + up_bound(pparam.get_upper_bound()), required(pparam.is_required()), + preset(pparam.get_default()), value(pparam.get_value()) + {} } TextSimulation::TextSimulation() : - _saved(true) -{ -} + _saved(true) +{} TextSimulation::~TextSimulation() -{ -} +{} -bool -TextSimulation::check_arguments_num(const Tokens& arguments, unsigned int num) +bool +TextSimulation::check_arguments_num(const Tokens& arguments, unsigned int num) { - if(arguments.size() < num) + if (arguments.size() < num) { ostringstream oss; oss << _("ERROR: this command requires at least ") << num << _(" arguments\n"); @@ -111,7 +107,7 @@ TextSimulation::check_arguments_num(const Tokens& arguments, unsigned int num) return false; } - else if(arguments.size() > num) + else if (arguments.size() > num) p_stderr(_("WARNING: some arguments will be ignored\n")); return true; @@ -120,12 +116,12 @@ TextSimulation::check_arguments_num(const Tokens& arguments, unsigned int num) bool TextSimulation::unsaved_ask_confirm() const { - if(!_saved) + if (!_saved) { p_stderr(_("WARNING: Simulation was not recently saved. " - "If you continue some changes to the simulation might be lost.\n")); + "If you continue some changes to the simulation might be lost.\n")); - for(bool bad_arg = true; bad_arg;) + for (bool bad_arg = true; bad_arg;) { p_stdout(_("Continue? [y/n] ")); @@ -133,12 +129,12 @@ TextSimulation::unsaved_ask_confirm() const Tokens tokens = tokenize(buf); - if(tokens.size() == 1 && tokens[0].size() == 1) + if (tokens.size() == 1 && tokens[0].size() == 1) { - if(tokens[0].lowercase() == _("n")) - return false; - else if(tokens[0].lowercase() == _("y")) - bad_arg = false; + if (tokens[0].lowercase() == _("n")) + return false; + else if (tokens[0].lowercase() == _("y")) + bad_arg = false; } } } @@ -150,8 +146,8 @@ template void TextSimulation::show(const Container& entities) { - for(unsigned int i = 0; i < entities.size(); ++i) - { + for (unsigned int i = 0; i < entities.size(); ++i) + { ostringstream oss; oss << i + 1 << ". " << entities[i]->get_name() << endl; p_stdout(oss.str()); @@ -163,9 +159,9 @@ namespace sgpem { template <> void - TextSimulation::show >(const vector& entities) + TextSimulation::show > (const vector& entities) { - for(unsigned int i = 0; i < entities.size(); ++i) + for (unsigned int i = 0; i < entities.size(); ++i) { ostringstream oss; oss << i + 1 << ". instant: " << entities[i]->get_instant() << endl; @@ -175,12 +171,12 @@ namespace sgpem template <> void - TextSimulation::show >(const vector& entities) + TextSimulation::show > (const vector& entities) { - for(unsigned int i = 0; i < entities.size(); ++i) + for (unsigned int i = 0; i < entities.size(); ++i) { - ostringstream oss; - + ostringstream oss; + oss << i + 1 << ". resource: " << entities[i]->get_resource_key() << endl; p_stdout(oss.str()); } @@ -188,21 +184,21 @@ namespace sgpem template <> void - TextSimulation::show >(const map& entities) + TextSimulation::show > (const map& entities) { typedef map::const_iterator ResourceIt; - - for(ResourceIt it = entities.begin(); it != entities.end(); ++it) + + for (ResourceIt it = entities.begin(); it != entities.end(); ++it) { - ostringstream oss; - + ostringstream oss; + oss << it->first << ". " << it->second->get_name(); oss << "[" << it->second->get_places() << "]" << endl; p_stdout(oss.str()); } } -} +} //~ namespace sgpem template void @@ -211,56 +207,56 @@ TextSimulation::get_parameter(CommandParameter& parameter) bool correct; do - { + { correct = true; ostringstream buf; - - if(parameter.required) + + if (parameter.required) buf << "*"; - - buf << parameter.description << " (range: [" << parameter.low_bound << ", " << - parameter.up_bound << "] current: " << parameter.value << ") : "; + + buf << parameter.description << " (range: [" << parameter.low_bound << ", " << + parameter.up_bound << "] current: " << parameter.value << ") : "; p_stdout(buf.str()); - + ustring input = readline(); - + T value; - - // FIXME semi-hack, it's a bit overkill to tokenize the string + + // FIXME semi-hack, it's a bit overkill to tokenize the string // to find if it's only composed of white spaces... // Indedeed there's a pro: by using extensively tokenize() we are more sure // it's correct ;-) - if(tokenize(input).size() > 0) + if (tokenize(input).size() > 0) { try - { - value = string_to(input); - - if(value > parameter.up_bound || value < parameter.low_bound) - { - p_stderr(_("ERROR: Provided value is out of range\n")); - correct = false; - } - } - catch(domain_error e) { - p_stderr(_("ERROR: Please provide a valid numeric value\n")); - correct = false; + value = string_to(input); + + if (value > parameter.up_bound || value < parameter.low_bound) + { + p_stderr(_("ERROR: Provided value is out of range\n")); + correct = false; + } + } + catch (domain_error e) + { + p_stderr(_("ERROR: Please provide a valid numeric value\n")); + correct = false; } - if(correct) - parameter.value = value; + if (correct) + parameter.value = value; } - else if(parameter.required) + else if (parameter.required) { p_stderr(_("ERROR: This is a mandatory attribute; you MUST provide a valid value!\n")); - + correct = false; } } - while(!correct); + while (!correct); } // Specializations need to go explicitly inside the namespace. why? @@ -272,31 +268,31 @@ namespace sgpem { bool loop = true; - while(loop) + while (loop) { ustring buf; - - if(parameter.required) - buf += "*"; - p_stdout(buf + parameter.description + - " (current: \"" + parameter.value + "\") : "); - + if (parameter.required) + buf += "*"; + + p_stdout(buf + parameter.description + + " (current: \"" + parameter.value + "\") : "); + buf = readline(); - - // FIXME semi-hack, it's a bit overkill to tokenize the string + + // FIXME semi-hack, it's a bit overkill to tokenize the string // to find if it's only composed of white spaces... // Indedeed there's a pro: by using extensively tokenize() we are more sure // it's correct ;-) Tokens tokens = tokenize(buf); - - if(tokens.size() == 0 && parameter.required) - p_stderr(_("ERROR: This is a mandatory atribute; you MUST provide a valid value!\n")); + + if (tokens.size() == 0 && parameter.required) + p_stderr(_("ERROR: This is a mandatory atribute; you MUST provide a valid value!\n")); else - { - // FIXME should we assign the entire line here or just a token? - parameter.value = buf; - loop = false; + { + // FIXME should we assign the entire line here or just a token? + parameter.value = buf; + loop = false; } } } @@ -310,52 +306,52 @@ namespace sgpem do { correct = true; - - ostringstream buf; - - if(parameter.required) - buf << "*"; - buf << parameter.description << - " (current: " << boolalpha << parameter.value << ") : "; - + ostringstream buf; + + if (parameter.required) + buf << "*"; + + buf << parameter.description << + " (current: " << boolalpha << parameter.value << ") : "; + p_stdout(buf.str()); - + ustring str = readline(); - - // FIXME semi-hack, it's a bit overkill to tokenize the string + + // FIXME semi-hack, it's a bit overkill to tokenize the string // to find if it's only composed of white spaces... // Indedeed there's a pro: by using extensively tokenize() we are more sure // it's correct ;-) Tokens tokens = tokenize(str); - - if(tokens.size() != 0) - { - try - { - parameter.value = string_to(str); - } - catch(domain_error e) - { - p_stderr(_("ERROR: Please provide a valid boolean value ('true' or 'false')\n")); - correct = false; - } - } - else if(parameter.required) + + if (tokens.size() != 0) { - p_stderr(_("ERROR: This is a mandatory atribute; you MUST provide a valid value!\n")); - correct = false; + try + { + parameter.value = string_to(str); + } + catch (domain_error e) + { + p_stderr(_("ERROR: Please provide a valid boolean value ('true' or 'false')\n")); + correct = false; + } + } + else if (parameter.required) + { + p_stderr(_("ERROR: This is a mandatory atribute; you MUST provide a valid value!\n")); + correct = false; } } - while(!correct); + while (!correct); } } - + void TextSimulation::on_run(const Tokens& arguments) { check_arguments_num(arguments, 0); - + // Listen for updates only during scheduling Simulation::get_instance().get_history().attach(*this); @@ -363,13 +359,13 @@ TextSimulation::on_run(const Tokens& arguments) { Simulation::get_instance().run(); } - catch(UserInterruptException e) + catch (UserInterruptException e) { p_stderr(_("ERROR: ")); p_stderr(e.what()); p_stderr(_("\nSimulation is now stopped\n")); } - catch(NullPolicyException e) + catch (NullPolicyException e) { p_stderr(_("ERROR: ")); p_stderr(e.what()); @@ -379,49 +375,49 @@ TextSimulation::on_run(const Tokens& arguments) Simulation::get_instance().get_history().detach(*this); } -void -TextSimulation::on_pause(const Tokens& arguments) +void +TextSimulation::on_pause(const Tokens& arguments) { check_arguments_num(arguments, 0); - + Simulation::get_instance().pause(); } void -TextSimulation::on_stop(const Tokens& arguments) +TextSimulation::on_stop(const Tokens& arguments) { check_arguments_num(arguments, 0); Simulation::get_instance().stop(); } -void -TextSimulation::on_configure_cpu_policy(const Tokens& arguments) +void +TextSimulation::on_configure_cpu_policy(const Tokens& arguments) { check_arguments_num(arguments, 0); CPUPolicy* policy = Simulation::get_instance().get_policy(); - if(policy == NULL) + if (policy == NULL) { p_stderr(_("ERROR: No policy actually selected for the simulation\n")); return; } - + PolicyParameters& parameters = policy->get_parameters(); p_stdout(_("Please provide a value for each attribute:\n")); p_stdout(_("Mandatory arguments are marked with an asterisk (*)\n\n")); p_stdout(_("Integer arguments:\n")); - + typedef map > IntParams; typedef map > FloatParams; typedef map > StringParams; IntParams int_params = parameters.get_registered_int_parameters(); - for(IntParams::iterator it = int_params.begin(); it != int_params.end();) + for (IntParams::iterator it = int_params.begin(); it != int_params.end();) { PolicyParameters::Parameter &p = it->second; CommandParameter cmd_p(p); @@ -439,10 +435,10 @@ TextSimulation::on_configure_cpu_policy(const Tokens& arguments) // I tried solving this issue by using templates, but to make // it work will require adding to PolicyParameters a member template // method with 2 specializations... - + FloatParams float_params = parameters.get_registered_float_parameters(); - for(FloatParams::iterator it = float_params.begin(); it != float_params.end();) + for (FloatParams::iterator it = float_params.begin(); it != float_params.end();) { PolicyParameters::Parameter &p = it->second; @@ -459,7 +455,7 @@ TextSimulation::on_configure_cpu_policy(const Tokens& arguments) StringParams string_params = parameters.get_registered_string_parameters(); - for(StringParams::iterator it = string_params.begin(); it != string_params.end();) + for (StringParams::iterator it = string_params.begin(); it != string_params.end();) { PolicyParameters::Parameter &p = it->second; @@ -478,119 +474,119 @@ void TextSimulation::on_help(const Tokens& arguments) { ustring command; - - if(arguments.size() > 0) + + if (arguments.size() > 0) { command = arguments[0].uppercase(); // print warning if necessary check_arguments_num(arguments, 1); } - if(command.size() == 0) + if (command.size() == 0) p_stdout(_("Avaiable commands:\nRUN\nSTOP\nPAUSE\n" - "CONFIGURE-CPU-POLICY\nHELP\nGET\nSET\nSHOW\nADD\n" - "REMOVE\nSAVE\nLOAD\nQUIT\n\n" - "HELP followed by a command name shows help about it.\n" - "ex. `HELP RUN` shows help about the command RUN\n")); - else if(command == "RUN") + "CONFIGURE-CPU-POLICY\nHELP\nGET\nSET\nSHOW\nADD\n" + "REMOVE\nSAVE\nLOAD\nQUIT\n\n" + "HELP followed by a command name shows help about it.\n" + "ex. `HELP RUN` shows help about the command RUN\n")); + else if (command == "RUN") p_stdout(_("-- RUN COMMAND --\nStarts the simulation. It can be " - "continuous or step-by-step depending on the mode configured with " - "SET CONTINUOUS (default=true).\n\n" - "The output of RUN is a snapshot of the state of the simulation at each " - "instant.\n" - "The instant 0 represents the initial state, " - "during which no process is running. The scheduler " - "activity begins at instant 1.\n")); - else if(command == "STOP") + "continuous or step-by-step depending on the mode configured with " + "SET CONTINUOUS (default=true).\n\n" + "The output of RUN is a snapshot of the state of the simulation at each " + "instant.\n" + "The instant 0 represents the initial state, " + "during which no process is running. The scheduler " + "activity begins at instant 1.\n")); + else if (command == "STOP") p_stdout(_("-- STOP COMMAND --\nStops the simulation. The next call to RUN will " - "bring the simulation to the first instant and start it.\n")); - else if(command == "PAUSE") + "bring the simulation to the first instant and start it.\n")); + else if (command == "PAUSE") p_stdout(_("-- PAUSE COMMAND --\nPauses the simulation. The next call to RUN will " - "continue it.\n")); - else if(command == "CONFIGURE-CPU-POLICY") + "continue it.\n")); + else if (command == "CONFIGURE-CPU-POLICY") p_stdout(_("-- CONFIGURE-CPU-POLICY COMMAND --\nConfigure parameters exposed by " - "the cpu policy.\n\nThis is currently the only way to control the behaviour of " - "cpu policies without modifying their source code.\n")); - else if(command == "HELP") + "the cpu policy.\n\nThis is currently the only way to control the behaviour of " + "cpu policies without modifying their source code.\n")); + else if (command == "HELP") p_stdout(_("-- HELP COMMAND --\nThe help you're reading.\n")); - else if(command == "GET") + else if (command == "GET") p_stdout(_("-- GET COMMAND --\nSyntax: GET \n" - "\twhere may be simulation-tick or continuous.\n")); - else if(command == "SET") + "\twhere may be simulation-tick or continuous.\n")); + else if (command == "SET") p_stdout(_("-- SET COMMAND --\nSyntax: SET [=] \n" - "\twhere may be simulation-tick, continuous or cpu-policy.\n")); - else if(command == "SHOW") + "\twhere may be simulation-tick, continuous or cpu-policy.\n")); + else if (command == "SHOW") p_stderr(_("-- SHOW COMMAND --\nDisplays the name of the entities (if available) " - "and other informations prefixed by its numeric identifier.\n\n" - "Syntax depends from entities being displayed:\n" - "`SHOW processes|resources|cpu-policies|resource-policies`\n" - "`SHOW threads ` with being the numeric identifier of " - "the parent process\n" - "`SHOW requests ` with being the numeric " - "identifier of the thread child of process identified by \n" - "`SHOW subrequests ` where the numeric ids " - "follow the same logic of the previous commands\n")); - else if(command == "ADD") + "and other informations prefixed by its numeric identifier.\n\n" + "Syntax depends from entities being displayed:\n" + "`SHOW processes|resources|cpu-policies|resource-policies`\n" + "`SHOW threads ` with being the numeric identifier of " + "the parent process\n" + "`SHOW requests ` with being the numeric " + "identifier of the thread child of process identified by \n" + "`SHOW subrequests ` where the numeric ids " + "follow the same logic of the previous commands\n")); + else if (command == "ADD") p_stderr(_("-- ADD COMMAND --\nAdds an entity by using a questionary-like approach.\n\n" - "Syntax depends from entity being added:\n" - "`ADD process|resource`\n" - "`ADD thread ` with being the numeric identifier of " - "the parent process\n" - "`ADD request ` with being the numeric " - "identifier of the thread child of process identified by \n" - "`ADD subrequest ` where the numeric ids " - "follow the same logic of the previous commands\n")); - else if(command == "REMOVE") + "Syntax depends from entity being added:\n" + "`ADD process|resource`\n" + "`ADD thread ` with being the numeric identifier of " + "the parent process\n" + "`ADD request ` with being the numeric " + "identifier of the thread child of process identified by \n" + "`ADD subrequest ` where the numeric ids " + "follow the same logic of the previous commands\n")); + else if (command == "REMOVE") p_stderr(_("-- REMOVE COMMAND --\nRemoves an entity.\n\n" - "Syntax depends from entity being removed:\n" - "`REMOVE process|resource ` where is the process or resource identifier\n" - "`REMOVE thread ` with being the identifier of " - "the parent process, and the id of the thread to be removed\n" - "`REMOVE request ` where the " - "numeric ids follow the same logic of the previous commands\n" - "`REMOVE subrequest ` where the " - "numeric ids follow the same logic of the previous commands\n")); - else if(command == "SAVE") + "Syntax depends from entity being removed:\n" + "`REMOVE process|resource ` where is the process or resource identifier\n" + "`REMOVE thread ` with being the identifier of " + "the parent process, and the id of the thread to be removed\n" + "`REMOVE request ` where the " + "numeric ids follow the same logic of the previous commands\n" + "`REMOVE subrequest ` where the " + "numeric ids follow the same logic of the previous commands\n")); + else if (command == "SAVE") p_stderr(_("-- SAVE COMMAND --\nSaves the simulation.\n\n" - "Syntax: SAVE \n")); - else if(command == "LOAD") + "Syntax: SAVE \n")); + else if (command == "LOAD") p_stderr(_("-- LOAD COMMAND --\nLoads the simulation.\n\n" - "Syntax: LOAD \n")); - else if(command == "QUIT") + "Syntax: LOAD \n")); + else if (command == "QUIT") p_stderr(_("-- QUIT COMMAND --\nGently closes the program.\n")); else - p_stderr(_("ERROR: Sorry, no help available for this command.\n")); -} - + p_stderr(_("ERROR: Sorry, no help available for this command.\n")); +} + void -TextSimulation::on_quit(const Tokens& arguments) +TextSimulation::on_quit(const Tokens& arguments) { check_arguments_num(arguments, 0); - if(!unsaved_ask_confirm()) + if (!unsaved_ask_confirm()) return; - + p_stdout(_("\n\n*** Thank you for using SGPEM by Sirius Cybernetics Corporation ***\n\n")); - + // Is this ok? Really? Oh, sure, if it we always did it in this way, it is surely a Good Thing! exit(1); } -void +void TextSimulation::on_get(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; - + ustring attr = arguments[0].uppercase(); - if(attr == "SIMULATION-TICK") + if (attr == "SIMULATION-TICK") { ostringstream oss; oss << "simulation-tick = " << Simulation::get_instance().get_timer() << "ms" << endl; p_stdout(oss.str()); } - else if(attr == "CONTINUOUS") + else if (attr == "CONTINUOUS") { ostringstream oss; oss << "continuous = " << boolalpha << Simulation::get_instance().get_mode() << endl; @@ -600,81 +596,81 @@ TextSimulation::on_get(const Tokens& arguments) p_stderr(_("ERROR: invalid attribute name. Accepted are: simulation-tick, continuous\n")); } -void +void TextSimulation::on_set(const Tokens& arguments) { - // handle the optional "=' (I knew that I was buying myself a problem when I + // handle the optional "=' (I knew that I was buying myself a problem when I // decided to support the assigment operator!) - if(arguments.size() >= 3) + if (arguments.size() >= 3) check_arguments_num(arguments, 3); - else if(!check_arguments_num(arguments, 2)) + else if (!check_arguments_num(arguments, 2)) return; - + ustring attr = arguments[0].uppercase(); - + ustring value; - if(arguments[1] == "=") + if (arguments[1] == "=") value = arguments[2]; else value = arguments[1]; - - if(attr == "SIMULATION-TICK") + + if (attr == "SIMULATION-TICK") { try { int timer = string_to(value); - if(timer < 0) - throw domain_error(""); - + if (timer < 0) + throw domain_error(""); + Simulation::get_instance().set_timer(timer); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: you must provide a valid unsigned integer value\n")); } - + } - else if(attr == "CPU-POLICY") + else if (attr == "CPU-POLICY") { int policy; - + try { policy = string_to(value) - 1; - if(policy < 0) - throw domain_error(""); + if (policy < 0) + throw domain_error(""); typedef vector ManagerVec; typedef vector::iterator CPUPolicyIt; - CPUPoliciesGatekeeper& gatekeeper = CPUPoliciesGatekeeper::get_instance(); + CPUPoliciesGatekeeper& gatekeeper = CPUPoliciesGatekeeper::get_instance(); ManagerVec managers = gatekeeper.get_registered(); - for(ManagerVec::iterator it = managers.begin(); it != managers.end(); ++it) + for (ManagerVec::iterator it = managers.begin(); it != managers.end(); ++it) { - vector policies = (*it)->get_avail_policies(); - for(CPUPolicyIt it = policies.begin(); it != policies.end(); ++it) - { - if(policy == 0) - Simulation::get_instance().set_policy(*it); - - --policy; - } - } + vector policies = (*it)->get_avail_policies(); + for (CPUPolicyIt it = policies.begin(); it != policies.end(); ++it) + { + if (policy == 0) + Simulation::get_instance().set_policy(*it); - if(policy >= 0) - throw domain_error(""); + --policy; + } + } + + if (policy >= 0) + throw domain_error(""); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: invalid unsigned integer or not a valid policy index\n")); } } - else if(attr == "CONTINUOUS") + else if (attr == "CONTINUOUS") { try { @@ -682,7 +678,7 @@ TextSimulation::on_set(const Tokens& arguments) Simulation::get_instance().set_mode(continuous); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: you must provide a valid boolean value ('true' or 'false')\n")); } @@ -691,22 +687,22 @@ TextSimulation::on_set(const Tokens& arguments) p_stderr(_("ERROR: invalid attribute name. Accepted are: simulation-tick, cpu-policy, continuous\n")); } -void +void TextSimulation::on_show(const Tokens& arguments) { - if(arguments.size() < 1) + if (arguments.size() < 1) { //print error check_arguments_num(arguments, 1); return; } - + //make a local copy which we'll probably modify Tokens args = arguments; ustring entities = args[0].uppercase(); args.erase(args.begin()); - + typedef void (TextSimulation::*f_ptr)(const Tokens&); map entities_handlers; @@ -717,11 +713,11 @@ TextSimulation::on_show(const Tokens& arguments) entities_handlers["SUBREQUESTS"] = &TextSimulation::on_show_subrequests; entities_handlers["CPU-POLICIES"] = &TextSimulation::on_show_cpu_policies; entities_handlers["RESOURCE-POLICIES"] = &TextSimulation::on_show_resource_policies; - - if(entities_handlers.find(entities) == entities_handlers.end()) + + if (entities_handlers.find(entities) == entities_handlers.end()) p_stderr(_("ERROR: invalid argument\n")); else - (this->*(entities_handlers[entities]))(args); + (this->*(entities_handlers[entities]))(args); } void @@ -732,7 +728,7 @@ TextSimulation::on_show_processes(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - show(processes); + show(processes); } void @@ -742,34 +738,34 @@ TextSimulation::on_show_resources(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Resources& resources = env.get_resources(); - - show(resources); + + show(resources); } void TextSimulation::on_show_threads(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; - + ustring process = arguments[0]; - + const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - + vector threads; - + try { int pid = string_to(process) - 1; threads = processes.at(pid)->get_threads(); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided process identifier is not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: this process identifier does not belong to an existing process\n")); return; @@ -777,12 +773,12 @@ TextSimulation::on_show_threads(const Tokens& arguments) show(threads); } - - + + void TextSimulation::on_show_requests(const Tokens& arguments) { - if(!check_arguments_num(arguments, 2)) + if (!check_arguments_num(arguments, 2)) return; ustring process = arguments[0]; @@ -791,7 +787,7 @@ TextSimulation::on_show_requests(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); vector requests; - + try { int pid = string_to(process) - 1; @@ -800,12 +796,12 @@ TextSimulation::on_show_requests(const Tokens& arguments) vector threads = processes.at(pid)->get_threads(); requests = threads.at(tid)->get_requests(); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -817,7 +813,7 @@ TextSimulation::on_show_requests(const Tokens& arguments) void TextSimulation::on_show_subrequests(const Tokens& arguments) { - if(!check_arguments_num(arguments, 3)) + if (!check_arguments_num(arguments, 3)) return; ustring process = arguments[0]; @@ -827,7 +823,7 @@ TextSimulation::on_show_subrequests(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); vector subrequests; - + try { int pid = string_to(process) - 1; @@ -838,12 +834,12 @@ TextSimulation::on_show_subrequests(const Tokens& arguments) vector requests = threads.at(tid)->get_requests(); subrequests = requests.at(rid)->get_subrequests(); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -857,18 +853,18 @@ TextSimulation::on_show_cpu_policies(const Tokens& arguments) { typedef vector ManagerVec; typedef vector::iterator CPUPolicyIt; - + check_arguments_num(arguments, 0); - CPUPoliciesGatekeeper& gatekeeper = CPUPoliciesGatekeeper::get_instance(); - + CPUPoliciesGatekeeper& gatekeeper = CPUPoliciesGatekeeper::get_instance(); + ManagerVec managers = gatekeeper.get_registered(); unsigned int index = 1; - for(ManagerVec::iterator it = managers.begin(); it != managers.end(); ++it) + for (ManagerVec::iterator it = managers.begin(); it != managers.end(); ++it) { vector policies = (*it)->get_avail_policies(); - for(CPUPolicyIt it = policies.begin(); it != policies.end(); ++it) + for (CPUPolicyIt it = policies.begin(); it != policies.end(); ++it) { ostringstream oss; oss << index << ". " << (*it)->get_name() << endl; @@ -877,7 +873,7 @@ TextSimulation::on_show_cpu_policies(const Tokens& arguments) p_stdout(oss.str()); ++index; } - } + } } void @@ -888,28 +884,28 @@ TextSimulation::on_show_resource_policies(const Tokens& arguments) p_stderr(_("FIXME: Not implemented\n")); } -void +void TextSimulation::on_add(const Tokens& arguments) { - if(arguments.size() < 1) + if (arguments.size() < 1) { //print error check_arguments_num(arguments, 1); return; } - - if(Simulation::get_instance().get_state() != Simulation::state_stopped) + + if (Simulation::get_instance().get_state() != Simulation::state_stopped) { p_stderr(_("WARNING: Simulation is not stopped, it will be automatically stopped\n")); Simulation::get_instance().stop(); } - + //make a local copy which we'll probably modify Tokens args = arguments; ustring entity = args[0].uppercase(); args.erase(args.begin()); - + typedef void (TextSimulation::*f_ptr)(const Tokens&); map entity_handlers; @@ -918,14 +914,14 @@ TextSimulation::on_add(const Tokens& arguments) entity_handlers["THREAD"] = &TextSimulation::on_add_thread; entity_handlers["REQUEST"] = &TextSimulation::on_add_request; entity_handlers["SUBREQUEST"] = &TextSimulation::on_add_subrequest; - - if(entity_handlers.find(entity) == entity_handlers.end()) + + if (entity_handlers.find(entity) == entity_handlers.end()) p_stderr(_("ERROR: invalid argument\n")); else - (this->*(entity_handlers[entity]))(args); + (this->*(entity_handlers[entity]))(args); } -void +void TextSimulation::on_add_process(const Tokens& arguments) { check_arguments_num(arguments, 0); @@ -942,8 +938,8 @@ TextSimulation::on_add_process(const Tokens& arguments) h.add_process(name.value, arrival_time.value, base_priority.value); } - -void + +void TextSimulation::on_add_resource(const Tokens& arguments) { check_arguments_num(arguments, 0); @@ -963,29 +959,29 @@ TextSimulation::on_add_resource(const Tokens& arguments) h.add_resource(name.value, preemptable.value, places.value, availability.value); } -void +void TextSimulation::on_add_thread(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; ustring process = arguments[0]; const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - + Process* p; - + try { p = processes.at(string_to(process) - 1); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1003,14 +999,14 @@ TextSimulation::on_add_thread(const Tokens& arguments) History& h = Simulation::get_instance().get_history(); - h.add_thread(name.value, *p, cpu_time.value, arrival_time.value, + h.add_thread(name.value, *p, cpu_time.value, arrival_time.value, base_priority.value); } - -void + +void TextSimulation::on_add_request(const Tokens& arguments) { - if(!check_arguments_num(arguments, 2)) + if (!check_arguments_num(arguments, 2)) return; ustring process = arguments[0]; @@ -1020,7 +1016,7 @@ TextSimulation::on_add_request(const Tokens& arguments) const Environment::Processes& processes = env.get_processes(); Thread* t; - + try { int pid = string_to(process) - 1; @@ -1029,12 +1025,12 @@ TextSimulation::on_add_request(const Tokens& arguments) vector threads = processes.at(pid)->get_threads(); t = threads.at(tid); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1049,10 +1045,10 @@ TextSimulation::on_add_request(const Tokens& arguments) h.add_request(*t, instant.value); } -void +void TextSimulation::on_add_subrequest(const Tokens& arguments) { - if(!check_arguments_num(arguments, 3)) + if (!check_arguments_num(arguments, 3)) return; ustring process = arguments[0]; @@ -1062,8 +1058,8 @@ TextSimulation::on_add_subrequest(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - Request* r; - + Request* r; + try { int pid = string_to(process) - 1; @@ -1075,12 +1071,12 @@ TextSimulation::on_add_subrequest(const Tokens& arguments) r = requests.at(rid); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1088,17 +1084,17 @@ TextSimulation::on_add_subrequest(const Tokens& arguments) CommandParameter resource_key(_("resource key"), 0, INT_MAX, true, 0); CommandParameter duration(_("duration"), 0, INT_MAX, true, 0); - + const Environment::Resources& resources = env.get_resources(); - + do { get_parameter(resource_key); - if(resources.find(resource_key.value) == resources.end()) + if (resources.find(resource_key.value) == resources.end()) p_stderr(_("ERROR: invalid resource identifier\n")); } - while(resources.find(resource_key.value) == resources.end()); + while (resources.find(resource_key.value) == resources.end()); get_parameter(duration); @@ -1107,25 +1103,25 @@ TextSimulation::on_add_subrequest(const Tokens& arguments) h.add_subrequest(*r, resource_key.value, duration.value); } -void +void TextSimulation::on_remove(const Tokens& arguments) { - if(arguments.size() < 1) + if (arguments.size() < 1) { //print error check_arguments_num(arguments, 1); return; } - - if(Simulation::get_instance().get_state() != Simulation::state_stopped) + + if (Simulation::get_instance().get_state() != Simulation::state_stopped) p_stderr(_("WARNING: Simulation is not stopped, it will be automatically stopped")); - + //make a local copy which we'll probably modify Tokens args = arguments; ustring entity = args[0].uppercase(); args.erase(args.begin()); - + typedef void (TextSimulation::*f_ptr)(const Tokens&); map entity_handlers; @@ -1134,36 +1130,36 @@ TextSimulation::on_remove(const Tokens& arguments) entity_handlers["THREAD"] = &TextSimulation::on_remove_thread; entity_handlers["REQUEST"] = &TextSimulation::on_remove_request; entity_handlers["SUBREQUEST"] = &TextSimulation::on_remove_subrequest; - - if(entity_handlers.find(entity) == entity_handlers.end()) + + if (entity_handlers.find(entity) == entity_handlers.end()) p_stderr(_("ERROR: invalid argument\n")); else - (this->*(entity_handlers[entity]))(args); + (this->*(entity_handlers[entity]))(args); } -void +void TextSimulation::on_remove_process(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; ustring process = arguments[0]; const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - + Process* p; - + try { p = processes.at(string_to(process) - 1); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1172,35 +1168,35 @@ TextSimulation::on_remove_process(const Tokens& arguments) History& h = Simulation::get_instance().get_history(); h.remove(*p); } - -void + +void TextSimulation::on_remove_resource(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; ustring resource = arguments[0]; History& h = Simulation::get_instance().get_history(); - + History::resource_key_t rid; - + try { rid = string_to(resource); - const Environment::Resources& resources = + const Environment::Resources& resources = h.get_environment_at(0).get_resources(); - if(resources.find(rid) == resources.end()) + if (resources.find(rid) == resources.end()) throw out_of_range(_("invalid resource id")); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1209,10 +1205,10 @@ TextSimulation::on_remove_resource(const Tokens& arguments) h.remove(rid); } -void +void TextSimulation::on_remove_thread(const Tokens& arguments) { - if(!check_arguments_num(arguments, 2)) + if (!check_arguments_num(arguments, 2)) return; ustring process = arguments[0]; @@ -1222,7 +1218,7 @@ TextSimulation::on_remove_thread(const Tokens& arguments) const Environment::Processes& processes = env.get_processes(); Thread* t; - + try { int pid = string_to(process) - 1; @@ -1231,12 +1227,12 @@ TextSimulation::on_remove_thread(const Tokens& arguments) vector threads = processes.at(pid)->get_threads(); t = threads.at(tid); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1245,11 +1241,11 @@ TextSimulation::on_remove_thread(const Tokens& arguments) History& h = Simulation::get_instance().get_history(); h.remove(*t); } - -void + +void TextSimulation::on_remove_request(const Tokens& arguments) { - if(!check_arguments_num(arguments, 3)) + if (!check_arguments_num(arguments, 3)) return; ustring process = arguments[0]; @@ -1259,8 +1255,8 @@ TextSimulation::on_remove_request(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - Request* r; - + Request* r; + try { int pid = string_to(process) - 1; @@ -1271,12 +1267,12 @@ TextSimulation::on_remove_request(const Tokens& arguments) vector requests = threads.at(tid)->get_requests(); r = requests.at(rid); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1286,10 +1282,10 @@ TextSimulation::on_remove_request(const Tokens& arguments) h.remove(*r); } -void +void TextSimulation::on_remove_subrequest(const Tokens& arguments) { - if(!check_arguments_num(arguments, 4)) + if (!check_arguments_num(arguments, 4)) return; ustring process = arguments[0]; @@ -1300,8 +1296,8 @@ TextSimulation::on_remove_subrequest(const Tokens& arguments) const Environment& env = Simulation::get_instance().get_history().get_environment_at(0); const Environment::Processes& processes = env.get_processes(); - SubRequest* r; - + SubRequest* r; + try { int pid = string_to(process) - 1; @@ -1314,12 +1310,12 @@ TextSimulation::on_remove_subrequest(const Tokens& arguments) vector subrequests = requests.at(rid)->get_subrequests(); r = subrequests.at(srid); } - catch(domain_error e) + catch (domain_error e) { p_stderr(_("ERROR: provided identifier(s) not a valid integer\n")); return; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: the identifier(s) do not belong to an existing entity\n")); return; @@ -1329,17 +1325,17 @@ TextSimulation::on_remove_subrequest(const Tokens& arguments) h.remove(*r); } -void +void TextSimulation::on_save(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; ustring filename = arguments[0]; try { - vector serializers = + vector serializers = SerializersGatekeeper::get_instance().get_registered(); // FIXME using the first serializer available, this @@ -1348,37 +1344,37 @@ TextSimulation::on_save(const Tokens& arguments) Serializer& serializer = *serializers.at(0); const History& history = Simulation::get_instance().get_history(); - + serializer.save_snapshot(filename, history); _saved = true; } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: No registered serializer available\n")); } - catch(SerializerError e) + catch (SerializerError e) { string msg = _("ERROR: "); - + p_stderr(msg + e.what() + "\n"); } } -void +void TextSimulation::on_load(const Tokens& arguments) { - if(!check_arguments_num(arguments, 1)) + if (!check_arguments_num(arguments, 1)) return; ustring filename = arguments[0]; - if(!unsaved_ask_confirm()) + if (!unsaved_ask_confirm()) return; - + try { - vector serializers = + vector serializers = SerializersGatekeeper::get_instance().get_registered(); // FIXME using the first serializer available, this @@ -1387,17 +1383,17 @@ TextSimulation::on_load(const Tokens& arguments) Serializer& serializer = *serializers.at(0); History& history = Simulation::get_instance().get_history(); - + serializer.restore_snapshot(filename, history); } - catch(out_of_range e) + catch (out_of_range e) { p_stderr(_("ERROR: No registered serializer available\n")); } - catch(SerializerError e) + catch (SerializerError e) { string msg = _("ERROR: "); - + p_stderr(msg + e.what() + "\n"); } } @@ -1444,32 +1440,32 @@ TextSimulation::parse_command(TextSimulation& sim, const ustring& str) command_handlers["SAVE"] = &TextSimulation::on_save; command_handlers["LOAD"] = &TextSimulation::on_load; command_handlers["QUIT"] = &TextSimulation::on_quit; - + Tokens arguments = tokenize(str); - - if(arguments.size() == 0) + + if (arguments.size() == 0) return; ustring key = arguments[0].uppercase(); - if(command_handlers.find(key) == command_handlers.end()) + if (command_handlers.find(key) == command_handlers.end()) { p_stderr(_("ERROR: command not supported\n")); return; } - + arguments.erase(arguments.begin()); - (sim.*(command_handlers[key]))(arguments); - - if(key == "ADD" || key == "REMOVE") + (sim.*(command_handlers[key]))(arguments); + + if (key == "ADD" || key == "REMOVE") sim._saved = false; -} +} static ostream& operator<<(ostream& os, Schedulable::state state) { - switch(state) + switch (state) { case Schedulable::state_running: os << "RUNNING"; @@ -1489,14 +1485,14 @@ operator<<(ostream& os, Schedulable::state state) default: os.setstate(ios_base::failbit); } - + return os; } static ostream& operator<<(ostream& os, Request::state state) { - switch(state) + switch (state) { case Request::state_unallocable: os << "UNALLOCABLE"; @@ -1516,7 +1512,7 @@ operator<<(ostream& os, Request::state state) default: os.setstate(ios_base::failbit); } - + return os; } @@ -1533,8 +1529,8 @@ TextSimulation::update(const History& changed_history) /// to instant (history.get_size() - 2). // this is a damn uint, so we must hack and hack int printed_instant; - - if(changed_history.get_size() > 1) + + if (changed_history.get_size() > 1) printed_instant = static_cast(changed_history.get_size()) - 2; else printed_instant = -1; @@ -1548,7 +1544,7 @@ TextSimulation::update(const History& changed_history) const Environment& env = changed_history.get_last_environment(); const ReadyQueue& q = env.get_sorted_queue(); - for(unsigned int i = 0; i < q.size(); ++i) + for (unsigned int i = 0; i < q.size(); ++i) { const Thread& t = q.get_item_at(i); @@ -1562,25 +1558,25 @@ TextSimulation::update(const History& changed_history) const Environment::Resources& resources = env.get_resources(); typedef Environment::Resources::const_iterator ResourceIt; - for(ResourceIt it = resources.begin(); it != resources.end(); ++it) + for (ResourceIt it = resources.begin(); it != resources.end(); ++it) { const Resource& r = *it->second; Environment::resource_key_t key = it->first; oss << " " << key << ") " << r.get_name() << _(", with "); - + oss << r.get_places() << _(" places\n"); p_stdout(oss.str()); oss.str(string()); - const Environment::SubRequestQueue& req_queue = + const Environment::SubRequestQueue& req_queue = env.get_request_queue(it->first); - + p_stdout(_("\t\t\tqueue: { ")); - - for(unsigned int i = 0; i < req_queue.size(); ++i) + + for (unsigned int i = 0; i < req_queue.size(); ++i) { if (i == r.get_places()) oss << " || "; @@ -1593,7 +1589,7 @@ TextSimulation::update(const History& changed_history) else oss << req_queue[i]->get_request().get_thread().get_name(); p_stdout(oss.str()); - oss.str(string()); + oss.str(string()); } p_stdout(" }\n"); @@ -1603,10 +1599,10 @@ TextSimulation::update(const History& changed_history) const Environment::Processes& processes = env.get_processes(); - for(unsigned int pi = 0; pi < processes.size(); ++pi) + for (unsigned int pi = 0; pi < processes.size(); ++pi) { Process& p = *processes[pi]; - + oss << " " << pi + 1 << ") " << p.get_name() << " "; oss << "[" << p.get_state() << "] "; oss << _("arriving at ") << p.get_arrival_time() << ", "; @@ -1617,9 +1613,9 @@ TextSimulation::update(const History& changed_history) p_stdout(oss.str()); oss.str(string()); - vector threads = p.get_threads(); + vector threads = p.get_threads(); - for(unsigned int ti = 0; ti < threads.size(); ++ti) + for (unsigned int ti = 0; ti < threads.size(); ++ti) { Thread& t = *threads[ti]; @@ -1635,32 +1631,32 @@ TextSimulation::update(const History& changed_history) vector requests = t.get_requests(); - for(unsigned int ri = 0; ri < requests.size(); ++ri) + for (unsigned int ri = 0; ri < requests.size(); ++ri) { - Request& r = *requests[ri]; + Request& r = *requests[ri]; - vector subrequests = r.get_subrequests(); + vector subrequests = r.get_subrequests(); - for(unsigned int sri = 0; sri < subrequests.size(); ++sri) - { - SubRequest& sr = *subrequests[sri]; - oss << _(" --> request ") << ri + 1 << "." << sri + 1 << ") "; - oss << _("at ") << r.get_instant() << " "; - ResourceIt point = resources.find(sr.get_resource_key()); - oss << _("for resource ") << (point->second)->get_name() << " "; - oss << _("with id ") << sr.get_resource_key() << " "; - oss << "[" << sr.get_state() << "] "; - oss << _("requiring ") << sr.get_length() << ", "; - oss << _("remaining ") << sr.get_remaining_time() << endl; + for (unsigned int sri = 0; sri < subrequests.size(); ++sri) + { + SubRequest& sr = *subrequests[sri]; + oss << _(" --> request ") << ri + 1 << "." << sri + 1 << ") "; + oss << _("at ") << r.get_instant() << " "; + ResourceIt point = resources.find(sr.get_resource_key()); + oss << _("for resource ") << (point->second)->get_name() << " "; + oss << _("with id ") << sr.get_resource_key() << " "; + oss << "[" << sr.get_state() << "] "; + oss << _("requiring ") << sr.get_length() << ", "; + oss << _("remaining ") << sr.get_remaining_time() << endl; - p_stdout(oss.str()); - oss.str(string()); - } + p_stdout(oss.str()); + oss.str(string()); + } } } } - + p_stdout("\n"); } diff --git a/src/text_simulation.hh b/src/text_simulation.hh index 80999b2..a76f315 100644 --- a/src/text_simulation.hh +++ b/src/text_simulation.hh @@ -84,7 +84,7 @@ namespace sgpem void on_stop(const Tokens& arguments); void on_configure_cpu_policy(const Tokens& arguments); void on_help(const Tokens& arguments); - void on_quit(const Tokens& arguments); + void on_quit(const Tokens& arguments); void on_get(const Tokens& arguments); void on_set(const Tokens& arguments); void on_show(const Tokens& arguments); @@ -101,7 +101,7 @@ namespace sgpem void on_add_thread(const Tokens& arguments); void on_add_request(const Tokens& arguments); void on_add_subrequest(const Tokens& arguments); - void on_remove(const Tokens& arguments); + void on_remove(const Tokens& arguments); void on_remove_process(const Tokens& arguments); void on_remove_resource(const Tokens& arguments); void on_remove_thread(const Tokens& arguments); @@ -109,8 +109,8 @@ namespace sgpem void on_remove_subrequest(const Tokens& arguments); void on_save(const Tokens& arguments); void on_load(const Tokens& arguments); - - // FIXME This is a temporary replacement for the + + // FIXME This is a temporary replacement for the // to-be written I/O layer static void p_stdout(const Glib::ustring& str); static void p_stderr(const Glib::ustring& str);