Statistics
| Branch: | Revision:

root / src / sim / csimulation.cc @ 49c66c64

History | View | Annotate | Download (29.4 KB)

1
//=========================================================================
2
//  CSIMULATION.CC - part of
3
//
4
//                  OMNeT++/OMNEST
5
//           Discrete System Simulation in C++
6
//
7
//   Definition of global object:
8
//    simulation
9
//
10
//   Member functions of
11
//    cSimulation  : holds modules and manages the simulation
12
//
13
//  Author: Andras Varga
14
//
15
//=========================================================================
16

    
17
/*--------------------------------------------------------------*
18
  Copyright (C) 1992-2008 Andras Varga
19
  Copyright (C) 2006-2008 OpenSim Ltd.
20

21
  This file is distributed WITHOUT ANY WARRANTY. See the file
22
  `license' for details on this and other legal matters.
23
*--------------------------------------------------------------*/
24

    
25
#include <string.h>
26
#include <stdio.h>
27
#include <algorithm>
28
#include "stringutil.h"
29
#include "cmodule.h"
30
#include "csimplemodule.h"
31
#include "cmessage.h"
32
#include "csimulation.h"
33
#include "cscheduler.h"
34
#include "cenvir.h"
35
#include "ccomponenttype.h"
36
#include "cstatistic.h"
37
#include "cexception.h"
38
#include "cparimpl.h"
39
#include "chasher.h"
40
#include "cconfiguration.h"
41
#include "ccoroutine.h"
42
#include "cthreadpool.h"
43
#include "cbarriermessage.h"
44
#include "cconfiguration.h"
45
#include "cconfigoption.h"
46
#include "clockedthreadpool.h"
47
#include "cspinningthreadpool.h"
48
#include "sysdep.h"
49

    
50

    
51

    
52
#ifdef WITH_PARSIM
53
#include "ccommbuffer.h"
54
#endif
55

    
56
#ifdef WITH_NETBUILDER
57
#include "netbuilder/cnedloader.h"
58
#endif
59

    
60
NAMESPACE_BEGIN
61

    
62
using std::ostream;
63

    
64
#ifdef DEVELOPER_DEBUG
65
#include <set>
66
extern std::set<cOwnedObject*> objectlist;
67
void printAllObjects();
68
#endif
69

    
70
Register_PerRunConfigOption(CFGID_USE_THREADPOOL, "use-thread-pool", CFG_BOOL, "false", "Use the threadpool");
71
Register_PerRunConfigOption(CFGID_THREADPOOL_CLASS, "thread-pool-class", CFG_STRING, "cSpinningThreadPool", "What class of threadpool to use");
72
Register_GlobalConfigOption(CFGID_THREADPOOL_CPU_ID_OFFSET, "cpu-id-offset", CFG_INT, "0", "Offset for Thread Affinity. (When running multiple instances of Horizon at once)");
73
Register_PerRunConfigOption(CFGID_SIMUL_THREADPOOL_SIZE, "thread-pool-size", CFG_STRING, "5", "Number of Threads in Threadpool");
74

    
75

    
76
cSimulation::cSimulation(const char *name, cEnvir *env) :
77
                cNamedObject(name, false), isrunning(false),
78
                endSimulation(false)
79
{
80
    ASSERT(cStaticFlag::isSet()); // cannot be instantiated as global variable
81

    
82
    ownEvPtr = env;
83

    
84
    activitymodp = NULL;
85
    cThreadPool::setContext(NULL);
86

    
87
    simulationstage = CTX_NONE;
88
    contexttype = CTX_NONE;
89

    
90
    systemmodp = NULL;
91
    schedulerp = NULL;
92
    threadPool = NULL;
93

    
94
    delta = 32;
95
    size = 0;
96
    last_id = 0; // vect[0] is not used for historical reasons
97
    vect = NULL;
98

    
99
    networktype = NULL;
100
    hasherp = NULL;
101

    
102
    //sim_time = SIMTIME_ZERO;
103
    cThreadPool::setSimTime(SIMTIME_ZERO);
104
    event_num = 0;
105

    
106
    msgQueue.setName("scheduled-events");
107
    take(&msgQueue);
108

    
109
    // install a default scheduler
110
    setScheduler(new cSequentialScheduler());
111

    
112
    eventsPerSimTimeInstance = 0;
113

    
114
    //calibrate stopwatch
115
    sequentialWatch.calibrateTSC();
116
}
117

    
118
cSimulation::~cSimulation()
119
{
120
    if (this==simPtr)
121
        throw cRuntimeError(this, "cannot delete the active simulation manager object");
122

    
123
    deleteNetwork();
124

    
125
    delete hasherp;
126
    delete schedulerp;
127
    delete ownEvPtr;
128
    drop(&msgQueue);
129
}
130

    
131
void cSimulation::setActiveSimulation(cSimulation *sim)
132
{
133
    simPtr = sim;
134
    evPtr = sim==NULL ? staticEvPtr : sim->ownEvPtr;
135
}
136

    
137
void cSimulation::setStaticEnvir(cEnvir *env)
138
{
139
    if (!env)
140
         throw cRuntimeError("cSimulation::setStaticEnvir(): argument cannot be NULL");
141
    staticEvPtr = env;
142
}
143

    
144
void cSimulation::forEachChild(cVisitor *v)
145
{
146
    if (systemmodp!=NULL)
147
        v->visit(systemmodp);
148
    v->visit(&msgQueue);
149
}
150

    
151
std::string cSimulation::getFullPath() const
152
{
153
    return getFullName();
154
}
155

    
156
static std::string xmlquote(const std::string& str)
157
{
158
    if (!strchr(str.c_str(), '<') && !strchr(str.c_str(), '>'))
159
        return str;
160

    
161
    std::stringstream out;
162
    for (const char *s=str.c_str(); *s; s++)
163
    {
164
        char c = *s;
165
        if (c=='<')
166
           out << "&lt;";
167
        else if (c=='>')
168
           out << "&gt;";
169
        else
170
           out << c;
171
    }
172
    return out.str();
173
}
174

    
175
class cSnapshotWriterVisitor : public cVisitor
176
{
177
  protected:
178
    ostream& os;
179
    int indentlevel;
180
  public:
181
    cSnapshotWriterVisitor(ostream& ostr) : os(ostr) {
182
        indentlevel = 0;
183
    }
184
    virtual void visit(cObject *obj) {
185
        std::string indent(2*indentlevel, ' ');
186
        os << indent << "<object class=\"" << obj->getClassName() << "\" fullpath=\"" << xmlquote(obj->getFullPath()) << "\">\n";
187
        os << indent << "  <info>" << xmlquote(obj->info()) << "</info>\n";
188
        std::string details = obj->detailedInfo();
189
        if (!details.empty())
190
            os << indent << "  <detailedinfo>" << xmlquote(details) << "</detailedinfo>\n";
191
        indentlevel++;
192
        obj->forEachChild(this);
193
        indentlevel--;
194
        os << indent << "</object>\n\n";
195

    
196
        if (os.fail()) throw EndTraversalException();
197
    }
198
};
199

    
200
bool cSimulation::snapshot(cObject *object, const char *label)
201
{
202
    if (!object)
203
        throw cRuntimeError("snapshot(): object pointer is NULL");
204

    
205
    ostream *osptr = ev.getStreamForSnapshot();
206
    if (!osptr)
207
        throw cRuntimeError("Could not create stream for snapshot");
208

    
209
    ostream& os = *osptr;
210

    
211
    os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
212
    os << "<snapshot\n";
213
    os << "    object=\"" << xmlquote(object->getFullPath()) << "\"\n";
214
    os << "    label=\"" << xmlquote(label?label:"") << "\"\n";
215
    os << "    simtime=\"" << xmlquote(SIMTIME_STR(simTime())) << "\"\n";
216
    os << "    network=\"" << xmlquote(networktype?networktype->getName():"") << "\"\n";
217
    os << "    >\n";
218

    
219
    cSnapshotWriterVisitor v(os);
220
    v.process(object);
221

    
222
    os << "</snapshot>\n";
223

    
224
    bool success = !os.fail();
225
    ev.releaseStreamForSnapshot(&os);
226

    
227
    if (!success)
228
        throw cRuntimeError("Could not write snapshot");
229
    return success;
230
}
231

    
232
void cSimulation::setScheduler(cScheduler *sch)
233
{
234
    if (systemmodp)
235
        throw cRuntimeError(this, "setScheduler(): cannot switch schedulers when a network is already set up");
236
    if (!sch)
237
        throw cRuntimeError(this, "setScheduler(): scheduler pointer is NULL");
238
    delete schedulerp;
239
    schedulerp = sch;
240
    schedulerp->setSimulation(this);
241
}
242

    
243
int cSimulation::loadNedSourceFolder(const char *folder)
244
{
245
#ifdef WITH_NETBUILDER
246
    return cNEDLoader::getInstance()->loadNedSourceFolder(folder);
247
#else
248
    throw cRuntimeError("cannot load NED files from `%s': simulation kernel was compiled without "
249
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)", folder);
250
#endif
251
}
252

    
253
void cSimulation::loadNedFile(const char *nedfile, const char *expectedPackage, bool isXML)
254
{
255
#ifdef WITH_NETBUILDER
256
    cNEDLoader::getInstance()->loadNedFile(nedfile, expectedPackage, isXML);
257
#else
258
    throw cRuntimeError("cannot load `%s': simulation kernel was compiled without "
259
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)", nedfile);
260
#endif
261
}
262

    
263
void cSimulation::loadNedText(const char *name, const char *nedtext, const char *expectedPackage, bool isXML)
264
{
265
#ifdef WITH_NETBUILDER
266
    cNEDLoader::getInstance()->loadNedText(name, nedtext, expectedPackage, isXML);
267
#else
268
    throw cRuntimeError("cannot source NED text: simulation kernel was compiled without "
269
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)");
270
#endif
271
}
272

    
273
void cSimulation::doneLoadingNedFiles()
274
{
275
#ifdef WITH_NETBUILDER
276
    cNEDLoader::getInstance()->doneLoadingNedFiles();
277
#endif
278
}
279

    
280
std::string cSimulation::getNedPackageForFolder(const char *folder)
281
{
282
#ifdef WITH_NETBUILDER
283
    return cNEDLoader::getInstance()->getNedPackageForFolder(folder);
284
#else
285
    return "-";
286
#endif
287
}
288

    
289
void cSimulation::clearLoadedNedFiles()
290
{
291
#ifdef WITH_NETBUILDER
292
    cNEDLoader::clear();
293
#endif
294
}
295

    
296
int cSimulation::registerModule(cModule *mod)
297
{
298
    // Insert module into the vector.
299
    // The module will get (last_id+1) as ID. We do not reuse "holes"
300
    // (empty slots) in the vector because we want the module ids to be
301
    // unique during the whole simulation.
302

    
303
    last_id++;
304

    
305
    if (last_id>=size)
306
    {
307
        // vector full, grow by delta
308
        cModule **v = new cModule *[size+delta];
309
        memcpy(v, vect, sizeof(cModule*)*size );
310
        for (int i=size; i<size+delta; i++) v[i]=NULL;
311
        delete [] vect;
312
        vect = v;
313
        size += delta;
314
    }
315
        ev.createRNGs();
316
    vect[last_id] = mod;
317
    return last_id;
318
}
319

    
320
void cSimulation::deregisterModule(cModule *mod)
321
{
322
    int id = mod->getId();
323
    vect[id] = NULL;
324

    
325
    if (mod==systemmodp)
326
    {
327
        drop(systemmodp);
328
        systemmodp = NULL;
329
    }
330
}
331

    
332
void cSimulation::setSystemModule(cModule *p)
333
{
334
    systemmodp = p;
335
    take(p);
336
}
337

    
338
cModule *cSimulation::getModuleByPath(const char *path) const
339
{
340
    if (opp_isempty(path))
341
        return NULL;
342

    
343
    // start tokenizing the path
344
    opp_string pathbuf(path);
345
    char *s = strtok(pathbuf.buffer(),".");
346

    
347
    // search starts from system module
348
    cModule *modp = getSystemModule();
349
    if (!modp)
350
        return NULL;
351

    
352
    // 1st component in the path may be the system module, skip it then
353
    if (modp->isName(s))
354
        s = strtok(NULL,".");
355

    
356
    // match components of the path
357
    while (s && modp)
358
    {
359
        char *b;
360
        if ((b=strchr(s,'['))==NULL)
361
        {
362
            modp = modp->getSubmodule(s);  // no index given
363
        }
364
        else
365
        {
366
            if (s[strlen(s)-1]!=']')
367
                throw cRuntimeError("getModuleByPath(): syntax error in path `%s'", path);
368
            *b='\0';
369
            modp = modp->getSubmodule(s,atoi(b+1));
370
        }
371
        s = strtok(NULL,".");
372
    }
373

    
374
    return modp;  // NULL if not found
375
}
376

    
377
void cSimulation::setupNetwork(cModuleType *network)
378
{
379
#ifdef DEVELOPER_DEBUG
380
    printf("DEBUG: before setupNetwork: %d objects\n", cOwnedObject::getLiveObjectCount());
381
    objectlist.clear();
382
#endif
383

    
384
    checkActive();
385
    if (!network)
386
        throw cRuntimeError(eNONET);
387
    if (!network->isNetwork())
388
        throw cRuntimeError("setupNetwork: `%s' is not a network", network->getFullName());
389

    
390
    // set cNetworkType pointer
391
    networktype = network;
392

    
393
    // just to be sure
394
    msgQueue.clear();
395
    cComponent::clearSignalState();
396

    
397
    simulationstage = CTX_BUILD;
398

    
399
    try
400
    {
401
        // set up the network by instantiating the toplevel module
402
        cContextTypeSwitcher tmp(CTX_BUILD);
403
        cModule *mod = networktype->create(networktype->getName(), NULL);
404
        mod->finalizeParameters();
405
        mod->buildInside();
406
    }
407
    catch (std::exception& e)
408
    {
409
        // Note: no deleteNetwork() call here. We could call it here, but it's
410
        // dangerous: module destructors may try to delete uninitialized pointers
411
        // and crash. (Often pointers incorrectly get initialized in initialize()
412
        // and not in the constructor.)
413
        throw;
414
    }
415
    //catch (...) -- this is not a good idea because it would make debugging more difficult
416
    //{
417
    //    deleteNetwork();
418
    //    throw cRuntimeError("unknown exception occurred");
419
    //}
420

    
421
    //printf("setupNetwork finished, cParImpl objects in use: %ld\n", cParImpl::getLiveParImplObjectCount());
422
}
423

    
424
void cSimulation::startRun()
425
{
426
    checkActive();
427
    // read config and setup thread pool
428
    setupThreadPool();
429

    
430
    // reset counters. Note msgQueue.clear() was already called from setupNetwork()
431
    cThreadPool::setSimTime(0.0);
432
    //sim_time = 0;
433
    event_num = 0; // initialize() has event number 0
434
    cMessage::resetMessageCounters();
435

    
436
    simulationstage = CTX_INITIALIZE;
437

    
438
    // init the scheduler. Note this may insert events into the FES (see e.g. cNullMessageProtocol)
439
    getScheduler()->startRun();
440

    
441
    // prepare simple modules for simulation run:
442
    //    1. create starter message for all modules,
443
    //    2. then call initialize() for them (recursively)
444
    //  This order is important because initialize() functions might contain
445
    //  send() calls which could otherwise insert msgs BEFORE starter messages
446
    //  for the destination module and cause trouble in cSimpleMod's activate().
447
    if (systemmodp)
448
    {
449
        cContextSwitcher tmp(systemmodp);
450
        systemmodp->scheduleStart(0);
451
        systemmodp->callInitialize();
452
    }
453

    
454
    event_num = 1; // events are numbered from 1
455

    
456
    simulationstage = CTX_EVENT;
457
    isrunning = true;
458
}
459

    
460
void cSimulation::callFinish()
461
{
462
    checkActive();
463

    
464
    simulationstage = CTX_FINISH;
465

    
466
    if (threaded)
467
        threadPool->shutdown();
468

    
469
    // call user-defined finish() functions for all modules recursively
470
    if (systemmodp)
471
    {
472
        systemmodp->callFinish();
473
    }
474
    isrunning = false;
475
}
476

    
477
void cSimulation::endRun()
478
{
479
    checkActive();
480
    getScheduler()->endRun();
481

    
482
    // move to deleteNetwork later?
483
    if (threaded) {
484
        threadPool->shutdown();
485
        delete threadPool;
486
    }
487
}
488

    
489
void cSimulation::deleteNetwork()
490
{
491
    if (!systemmodp)
492
        return;  // network already deleted
493

    
494
    if (getContextModule()!=NULL)
495
        throw cRuntimeError("Attempt to delete network during simulation");
496

    
497
    simulationstage = CTX_CLEANUP;
498

    
499
    // delete all modules recursively
500
    systemmodp->deleteModule();
501

    
502
    // make sure it was successful
503
    for (int i=1; i<size; i++)
504
        ASSERT(vect[i]==NULL);
505

    
506
    // and clean up
507
    delete [] vect;
508
    vect = NULL;
509
    size = 0;
510
    last_id = 0;
511

    
512
    networktype = NULL;
513

    
514
    //FIXME todo delete cParImpl caches too (cParImplCache, cParImplCache2)
515
    cModule::clearNamePools();
516

    
517
    // clear remaining messages (module dtors may have cancelled & deleted some of them)
518
    msgQueue.clear();
519

    
520
    simulationstage = CTX_NONE;
521

    
522
#ifdef DEVELOPER_DEBUG
523
    printf("DEBUG: after deleteNetwork: %d objects\n", cOwnedObject::getLiveObjectCount());
524
    printAllObjects();
525
#endif
526

    
527
}
528

    
529
cSimpleModule *cSimulation::selectNextModule()
530
{
531
    assert(false); //Do not call the scheduler from here.
532
    // determine next event. Normally (with sequential simulation),
533
    // the scheduler just returns msgQueue->peekFirst().
534
    cMessage *msg = schedulerp->getNextEvent();
535
    if (!msg)
536
        return NULL; // scheduler got interrupted while waiting
537

    
538
    // check if destination module exists and is still running
539
    cSimpleModule *modp = (cSimpleModule *)vect[msg->getArrivalModuleId()];
540
    if (!modp || modp->isTerminated())
541
    {
542
        // Deleted/ended modules may have self-messages and sent messages
543
        // pending for them. Here we choose just to ignore them (delete them without
544
        // any error or warning). Rationale: if we thew an error here, it would
545
        // be very difficult to delete compound modules in which simple modules
546
        // send messages to one another -- each and every simple module
547
        // would have to be notified in advance that they're "shutting down",
548
        // and even then, deletion could progress only after waiting the maximum
549
        // propagation delay to elapse.
550
        delete msgQueue.removeFirst();
551
        return selectNextModule();
552
    }
553

    
554
    // advance simulation time
555
    //sim_time = msg->getArrivalTime();
556
    cThreadPool::setSimTime(msg->getArrivalTime());
557
    return modp;
558
}
559

    
560
cMessage *cSimulation::guessNextEvent()
561
{
562
    // determine the probable next event. No call to cSheduler!
563
    // TBD if this event is "not good" (no module or module ended),
564
    // we might look for another event, but this is not done right now.
565
    return msgQueue.peekFirst();
566
}
567

    
568
simtime_t cSimulation::guessNextSimtime()
569
{
570
    cMessage *msg = guessNextEvent();
571
    return msg==NULL ? -1 : msg->getArrivalTime();
572
}
573

    
574
cSimpleModule *cSimulation::guessNextModule()
575
{
576
    cMessage *msg = guessNextEvent();
577
    if (!msg)
578
        return NULL;
579

    
580
    // check if dest module exists and still running
581
    if (msg->getArrivalModuleId()==-1)
582
        return NULL;
583
    cSimpleModule *modp = (cSimpleModule *)vect[msg->getArrivalModuleId()];
584
    if (!modp || modp->isTerminated())
585
        return NULL;
586
    return modp;
587
}
588

    
589
void cSimulation::transferTo(cSimpleModule *modp)
590
{
591
    if (modp==NULL)
592
        throw cRuntimeError("transferTo(): attempt to transfer to NULL");
593

    
594
    // switch to activity() of the simple module
595
    exception = NULL;
596
    activitymodp = modp;
597
    cCoroutine::switchTo(modp->coroutine);
598

    
599
    if (modp->hasStackOverflow())
600
        throw cRuntimeError("Stack violation in module (%s)%s: module stack too small? "
601
                            "Try increasing it in the class' Module_Class_Members() or constructor",
602
                            modp->getClassName(), modp->getFullPath().c_str());
603

    
604
    // if exception occurred in activity(), re-throw it. This allows us to handle
605
    // handleMessage() and activity() in an uniform way in the upper layer.
606
    if (exception)
607
    {
608
        cException *e = exception;
609
        exception = NULL;
610

    
611
        // ok, so we have an exception *pointer*, but we have to throw further
612
        // by *value*, and possibly without leaking it. Hence the following magic...
613
        if (dynamic_cast<cDeleteModuleException *>(e))
614
        {
615
            cDeleteModuleException e2(*(cDeleteModuleException *)e);
616
            delete e;
617
            throw e2;
618
        }
619
        else if (dynamic_cast<cTerminationException *>(e))
620
        {
621
            cTerminationException e2(*(cTerminationException *)e);
622
            delete e;
623
            throw e2;
624
        }
625
        else if (dynamic_cast<cRuntimeError *>(e))
626
        {
627
            cRuntimeError e2(*(cRuntimeError *)e);
628
            delete e;
629
            throw e2;
630
        }
631
        else
632
        {
633
            cException e2(*(cException *)e);
634
            delete e;
635
            throw e2;
636
        }
637
    }
638
}
639

    
640
void cSimulation::doOneEvent(cMessage* msg)
641
{
642
    cSimpleModule* mod = NULL;
643

    
644
#ifndef NDEBUG
645
    checkActive();
646
#endif
647

    
648
    try
649
    {
650
        // a worker signaled to shutdown the simulation
651
        if(endSimulation)
652
            throw cTerminationException(eENDSIM);
653

    
654
        // update the number of events that occur at the same simtime
655
        simtime_t currentTime = cThreadPool::getSimTime();
656
        if (currentTime < msg->getArrivalTime())
657
            eventsPerSimTimeInstance = 0;
658
        else
659
            eventsPerSimTimeInstance++;
660

    
661
        // remember how many events at this simtime instance have already been executed
662
        msg->setExecutionOrderId(eventsPerSimTimeInstance);
663

    
664
        // finally, advance Simulation Time
665
        cThreadPool::setSimTime(msg->getArrivalTime());
666

    
667
        // Update mod pointer:
668
        mod = (cSimpleModule*) simulation.vect[msg->getArrivalModuleId()];
669
        // notify the environment about the event (writes eventlog, etc.)
670
        if (!mod) {
671
            throw cRuntimeError("Module was deleted during Simulation. This is not supported by Horizon.");
672
        }
673
        if (mod->usesActivity()) {
674
            throw cRuntimeError("Activity-Model not supported with Horizon.");
675
        }
676

    
677
                // set the context for sequential execution
678
                setContext(mod);
679
                setContextType(CTX_EVENT);
680

    
681
                simtime_t duration = msg->getEventDuration();
682
                bool sequentialExecution = (duration == SimTime::simTimeSequentialExecution);
683

    
684
                if (sequentialExecution)
685
                        duration = SimTime::simTimeZero;
686

    
687
                if (duration < SimTime::simTimeZero)
688
                {
689
                        throw cRuntimeError("negative event duration not allowed.");
690
                }
691

    
692
                bool mayPar = mod->mayParallelize(msg, duration);
693

    
694
                cMessage *msg2=msgQueue.removeFirst();
695
                assert(msg==msg2);
696

    
697
                // execute this event in parallel
698
                if (mayPar && threaded && !sequentialExecution)
699
                {
700
                        //printf("Offloading: %s\n",mod->getName());
701
                        threadPool->insertTask(msg, duration);
702
                        // the threadpool unsets the module busy after it finishes the event
703
                }
704
                else
705
                {
706
                        EVCB.simulationEvent(msg);
707

    
708
                        msg->setPreviousEventNumber(event_num);
709

    
710
                        sequentialWatch.reset();
711
                        sequentialWatch.startTicking();
712
                        // take ownership in callHandleMessage after concurrency check
713
                        mod->callHandleMessage(msg);
714
                        sequentialWatch.stopTicking();
715

    
716
                        //Store measured complexity and write to file
717
                        EVCB.simulationEventEnd(sequentialWatch.getTicksTime());
718

    
719
                        // take ownership in callHandleMessage after concurrency check
720
                        // unset busy to release module for further events
721
                        mod->unsetBusy();
722
                }
723

    
724
        //We have handled the Message, return
725
        setGlobalContext();
726
        event_num++;
727
        return;
728
    }
729
    catch (cDeleteModuleException& e)
730
    {
731
        assert(false); //not implemented
732
        setGlobalContext();
733
        mod->deleteModule();
734
    }
735
    catch (cException&)
736
    {
737
        // restore global context before throwing the exception further
738
        setGlobalContext();
739
        throw;
740
    }
741
    catch (std::exception& e)
742
    {
743
        // restore global context before throwing the exception further
744
        // but wrap into a cRuntimeError which captures the module before that
745
        cRuntimeError e2("%s: %s", opp_typename(typeid(e)), e.what());
746
        setGlobalContext();
747
        throw e2;
748
    }
749
}
750

    
751
void cSimulation::transferToMain()
752
{
753
    if (activitymodp!=NULL)
754
    {
755
        activitymodp = NULL;
756
        cCoroutine::switchToMain();     // stack switch
757
    }
758
}
759

    
760
void cSimulation::setContext(cComponent *p)
761
{
762
    cThreadPool::setContext(p);
763
    cThreadPool::setDefaultOwner(p);
764
}
765

    
766
cModule *cSimulation::getContextModule() const
767
{
768
    cComponent* ctxMod = cThreadPool::getContext();
769
    // cannot go inline (upward cast would require including cmodule.h in csimulation.h)
770
    if (!ctxMod || !ctxMod->isModule())
771
        return NULL;
772
    return (cModule *) ctxMod;
773
}
774

    
775
cSimpleModule *cSimulation::getContextSimpleModule() const
776
{
777
    cComponent* ctxMod = cThreadPool::getContext();
778
    // cannot go inline (upward cast would require including cmodule.h in csimulation.h)
779
    if (!ctxMod || !ctxMod->isModule() || !((cModule *) ctxMod)->isSimple())
780
        return NULL;
781
    return (cSimpleModule *) ctxMod;
782
}
783

    
784
unsigned long cSimulation::getUniqueNumber()
785
{
786
    return ev.getUniqueNumber();
787
}
788

    
789
void cSimulation::setHasher(cHasher *hasher)
790
{
791
    if (hasherp)
792
        delete hasherp;
793
    hasherp = hasher;
794
}
795

    
796
void cSimulation::insertMsg(cMessage *msg)
797
{
798
    msg->setPreviousEventNumber(event_num);
799
    simulation.msgQueue.insert(msg);
800
}
801

    
802
void cSimulation::setupThreadPool() {
803
    threaded = ev.getConfig()->getAsBool(CFGID_USE_THREADPOOL);
804

    
805
#ifdef ENABLE_OWNERSHIP
806
    if (threaded) {
807
        throw cRuntimeError(this, "Ownership Model is incompatible with threaded "
808
                "architecture of Horizon. Please disable threading or ownership");
809
    }
810
#endif
811

    
812
    if (threaded) {
813
        std::string threadPoolClass = ev.getConfig()->getAsString(
814
                CFGID_THREADPOOL_CLASS);
815
        if (threadPoolClass.compare("cLockedThreadPool") == 0) {
816
            threadPool = new cLockedThreadPool();
817
        } else if (threadPoolClass.compare("cSpinningThreadPool") == 0) {
818
            threadPool = new cSpinningThreadPool();
819
        } else {
820
            printf("WARNING: Threadpool class selected does not exist!\n");
821
            printf("Falling back to default (cSpinningThreadPool)\n");
822
            sleep(3);
823
            threadPool = new cSpinningThreadPool();
824
        }
825
        threadPool->activate();
826
    } else {
827
        //
828
        // set the cpu-id offset (used for demo reasons only)
829
        //
830
        unsigned cpuIdOffset = ev.getConfig()->getAsInt(
831
                CFGID_THREADPOOL_CPU_ID_OFFSET);
832
        unsigned cpuCount = (unsigned) sysconf(_SC_NPROCESSORS_ONLN);
833
        if (cpuIdOffset >= cpuCount) {
834
            throw cRuntimeError("Mis-configured CPU-id offset: exceeding number of"
835
                                " physical CPUs");
836
        }
837
        thread_set_affinity(pthread_self(), 0 + cpuIdOffset);
838
    }
839
}
840

    
841
unsigned int cSimulation::getNextExecutionOrderId(cMessage* msg) {
842
    simtime_t currentTime = cThreadPool::getSimTime();
843
    if (currentTime < msg->getArrivalTime())
844
        return 0;
845
    else
846
        return eventsPerSimTimeInstance + 1;
847
}
848

    
849
//----
850

    
851
/**
852
 * A dummy implementation of cEnvir, only provided so that one
853
 * can use simulation library classes outside simulations, that is,
854
 * in programs that only link with the simulation library (<i>sim_std</i>)
855
 * and not with the <i>envir</i>, <i>cmdenv</i>, <i>tkenv</i>,
856
 * etc. libraries.
857
 *
858
 * Many simulation library classes make calls to <i>ev</i> methods,
859
 * which would crash if <tt>evPtr</tt> was NULL; one example is
860
 * cObject's destructor which contains an <tt>ev.objectDeleted()</tt>.
861
 * The solution provided here is that <tt>evPtr</tt> is initialized
862
 * to point to a StaticEnv instance, thus enabling library classes to work.
863
 *
864
 * StaticEnv methods either do nothing, or throw an "unsupported method"
865
 * exception, so StaticEnv is only useful for the most basic usage scenarios.
866
 * For anything more complicated, <tt>evPtr</tt> must be set in <tt>main()</tt>
867
 * to point to a proper cEnvir implementation, like the Cmdenv or
868
 * Tkenv classes. (The <i>envir</i> library provides a <tt>main()</tt>
869
 * which does exactly that.)
870
 *
871
 * @ingroup Envir
872
 */
873
class StaticEnv : public cEnvir
874
{
875
  protected:
876
    void unsupported() const {throw opp_runtime_error("StaticEnv: unsupported method called");}
877

    
878
    virtual void sputn(const char *s, int n) {(void) ::fwrite(s,1,n,stdout);}
879
    virtual void putsmsg(const char *msg) {::printf("\n<!> %s\n\n", msg);}
880
    virtual bool askyesno(const char *msg)  {unsupported(); return false;}
881

    
882
  public:
883
    // constructor, destructor
884
    StaticEnv() {}
885
    virtual ~StaticEnv() {}
886

    
887
    // eventlog callback interface
888
    virtual void objectDeleted(cObject *object) {}
889
    virtual void simulationEvent(cMessage *msg)  {}
890
    virtual void simulationEventEnd(double complexity)  {}
891
    virtual void messageSent_OBSOLETE(cMessage *msg, cGate *directToGate=NULL)  {}
892
    virtual void messageScheduled(cMessage *msg)  {}
893
    virtual void messageCancelled(cMessage *msg)  {}
894
    virtual void beginSend(cMessage *msg)  {}
895
    virtual void messageSendDirect(cMessage *msg, cGate *toGate, simtime_t propagationDelay, simtime_t transmissionDelay)  {}
896
    virtual void messageSendHop(cMessage *msg, cGate *srcGate)  {}
897
    virtual void messageSendHop(cMessage *msg, cGate *srcGate, simtime_t propagationDelay, simtime_t transmissionDelay)  {}
898
    virtual void endSend(cMessage *msg)  {}
899
    virtual void messageDeleted(cMessage *msg)  {}
900
    virtual void moduleReparented(cModule *module, cModule *oldparent)  {}
901
    virtual void componentMethodBegin(cComponent *from, cComponent *to, const char *methodFmt, va_list va, bool silent)  {}
902
    virtual void componentMethodEnd()  {}
903
    virtual void moduleCreated(cModule *newmodule)  {}
904
    virtual void moduleDeleted(cModule *module)  {}
905
    virtual void gateCreated(cGate *newgate)  {}
906
    virtual void gateDeleted(cGate *gate)  {}
907
    virtual void connectionCreated(cGate *srcgate)  {}
908
    virtual void connectionDeleted(cGate *srcgate)  {}
909
    virtual void displayStringChanged(cComponent *component)  {}
910
    virtual void undisposedObject(cObject *obj);
911

    
912
     // configuration, model parameters
913
    virtual void configure(cComponent *component) {}
914
    virtual void readParameter(cPar *parameter)  {unsupported();}
915
    virtual bool isModuleLocal(cModule *parentmod, const char *modname, int index)  {return true;}
916
    virtual cXMLElement *getXMLDocument(const char *filename, const char *path=NULL)  {unsupported(); return NULL;}
917
    virtual void forgetXMLDocument(const char *filename) {}
918
    virtual void flushXMLDocumentCache() {}
919
    virtual unsigned getExtraStackForEnvir() const  {return 0;}
920
    virtual cConfiguration *getConfig()  {unsupported(); return NULL;}
921
    virtual bool isGUI() const  {return false;}
922

    
923
    // UI functions (see also protected ones)
924
    virtual void bubble(cComponent *component, const char *text)  {}
925
    virtual std::string gets(const char *prompt, const char *defaultreply=NULL)  {unsupported(); return "";}
926
    virtual cEnvir& flush()  {::fflush(stdout); return *this;}
927

    
928
    // RNGs
929
    virtual int getNumRNGsPerModule() const {return 0;}
930
    virtual cRNG *getRNG(int k)  {unsupported(); return NULL;}
931
    virtual void getRNGMappingFor(cComponent *component)  {component->setRNGMap(0,NULL);}
932
        virtual void createRNGs() {unsupported();}
933

    
934
    // output vectors
935
    virtual void *registerOutputVector(const char *modulename, const char *vectorname)  {return NULL;}
936
    virtual void deregisterOutputVector(void *vechandle)  {}
937
    virtual void setVectorAttribute(void *vechandle, const char *name, const char *value)  {}
938
    virtual bool recordInOutputVector(void *vechandle, simtime_t t, double value)  {return false;}
939

    
940
    // output scalars
941
    virtual void recordScalar(cComponent *component, const char *name, double value, opp_string_map *attributes=NULL)  {}
942
    virtual void recordStatistic(cComponent *component, const char *name, cStatistic *statistic, opp_string_map *attributes=NULL)  {}
943

    
944
    // snapshot file
945
    virtual std::ostream *getStreamForSnapshot()  {unsupported(); return NULL;}
946
    virtual void releaseStreamForSnapshot(std::ostream *os)  {unsupported();}
947

    
948
    // misc
949
    virtual int getArgCount() const  {unsupported(); return 0;}
950
    virtual char **getArgVector() const  {unsupported(); return NULL;}
951
    virtual int getParsimProcId() const {return 0;}
952
    virtual int getParsimNumPartitions() const {return 1;}
953
    virtual unsigned long getUniqueNumber()  {unsupported(); return 0;}
954
    virtual bool idle()  {return false;}
955
};
956

    
957
void StaticEnv::undisposedObject(cObject *obj)
958
{
959
    if (!cStaticFlag::isSet())
960
    {
961
        ::printf("<!> WARNING: global object variable (DISCOURAGED) detected: "
962
                 "(%s)`%s' at %p\n", obj->getClassName(), obj->getFullPath().c_str(), obj);
963
    }
964
}
965

    
966
static StaticEnv staticEnv;
967

    
968
// cSimulation's global variables
969
cEnvir *cSimulation::evPtr = &staticEnv;
970
cEnvir *cSimulation::staticEvPtr = &staticEnv;
971

    
972
cSimulation *cSimulation::simPtr = NULL;
973

    
974

    
975
NAMESPACE_END
976