📄 gamanager.cpp
字号:
/*************************************************************************** gamanager.cpp - description ------------------- begin : Sat Feb 16 2002 copyright : (C) 2002 by R黡iger Koch email : rkoch@rkoch.org ***************************************************************************//*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/using namespace std;#include "gamanager.h"#include <iostream>#include <sys/times.h>#include <signal.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>GAManager *GAManager::theGAManager;bool GAManager::run = true;bool GAManager::isManager = true;GAManager::GAManager(){ genome = new Genome(); theGAManager = this; signal(SIGALRM, timeout); signal(SIGHUP, simStop); signal(SIGINT, simStop);}GAManager::~GAManager(){}/** Fork a new child for each generation. We do this to avoid trouble with * mem leaks, Amygdala initialization... Let the OS clean things up. */int GAManager::Loop(string uri, AmTimeInt maxSimTime, AmTimeInt maxRunTime){ while(run) { pid_t child = fork(); if(child == -1) { throw string("Cannot fork a child"); return -1; } if(child>0){ // parent int status; waitpid(child, &status, WUNTRACED); } else { alarm(500); isManager = false; Setup(uri); Run(maxSimTime, maxRunTime); return EXIT_SUCCESS; } }}void GAManager::Run(AmTimeInt maxSimTime, AmTimeInt maxRunTime){ alarm(maxRunTime); NN->Run(maxSimTime); finalize();}void GAManager::finalize(){ struct tms cpuTime; times(&cpuTime); // used to calculate fitness unsigned int score = GetScore(); cout << "CPU Time was: " << (cpuTime.tms_stime + cpuTime.tms_utime)/100. << " s. Score: " << score << endl; genome->submit(score); exit(0);}void GAManager::timeout(int signum){ cout << "Timeout reached, finalizing...\n"; theGAManager->finalize();}void GAManager::simStop(int signum){ if(isManager) { if(!run) return; // Already got a signal cout << "Received signal " << signum << ". Stopping the simulation. Hold on...\n"; run = false; } else { cout << "I am a worker. Redirecting the signal to the manager" << endl; kill(getppid(), signum); }}Network* GAManager::getNetwork(){ return NN;}void GAManager::GenomeFormat(string format){ genome->Format(format);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -