Project

General

Profile

Statistics
| Branch: | Revision:

root / src / sim / casyncmodule.cc @ d669a8ab

History | View | Annotate | Download (17.3 KB)

1
//=========================================================================
2
//  CASYNCMODULE.CC - part of
3
//
4
//                  OMNeT++/OMNEST
5
//           Discrete System Simulation in C++
6
//
7
//
8
//   Member functions of
9
//    cAsyncModule : derived class of cSimpleModule for asynchronous event handling
10
//
11
//  Author: Georg Kunz
12
//
13
//=========================================================================
14

    
15
/*--------------------------------------------------------------*
16
  Copyright (C) 2009 Georg Kunz
17

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

    
22
#include <cstring>
23
#include <sstream>
24
#include <stdlib.h>
25

    
26
#include "casyncmodule.h"
27
#include "cthreadpool.h"
28
#include "cconfiguration.h"
29
#include "cconfigoption.h"
30
#include "../envir/envirbase.h"
31
#include "cstringtokenizer.h"
32

    
33
Register_PerRunConfigOption(CFGID_ASYNCMODULE_PARZERODUR, "parallelize-zero-duration-events", CFG_BOOL, "false", "Parallelize Events with zero duration");
34
Register_PerObjectConfigOption(CFGID_NUM_LOCAL_RNGS, "number-local-rngs", CFG_INT, "1", "Number of RNGS per module");
35
Register_PerObjectConfigOption(CFGID_LOCAL_RNG_SEED, "local-rng-seed", CFG_STRING, "", "A whitespace seperated list of the seeds for each RNG of the corresponding module, eg '24 232 342 auto 342'");
36

    
37

    
38
cAsyncModule::cAsyncModule(const char *name, cModule *parent, unsigned stacksize) :
39
                t_end(0.0)
40
{
41
        //
42
        // find out if events with 0 durations should also be parallelized?
43
        //
44
        parZeroDur = ev.getConfig()->getAsBool(CFGID_ASYNCMODULE_PARZERODUR);
45

    
46
        //
47
        // init state flag to non-busy since no thread is active yet
48
        //
49
        AO_store(&busy, 0);
50

    
51
        //
52
        // needs to be initialized here for use during model initialization
53
        //
54
        scheduledMessageCount = 0;
55
    currentEventPriority = 0;
56

    
57
        //
58
        // initialize with the current time. This variable is already used when
59
        // scheduling events during the initialization phase of the simulation.
60
        // Hence, it needs to be initialized. However, we cannot assume 0 here since
61
        // the constructor is also called during dynamic module creation at any
62
        // point in time during the simulation.
63
        //
64
        now = simTime();
65

    
66
}
67

    
68

    
69
cAsyncModule::~cAsyncModule()
70
{
71
  delete numGen;
72
}
73

    
74
void cAsyncModule::initLocalRNGs()
75
{
76
    //TODO
77
    unsigned nrNumGens;
78
    unsigned long * seeds;
79

    
80
    //
81
    // how many local random number generators do we need?
82
    // default is 1
83
    //
84
    nrNumGens = ev.getConfig()->parseLong(
85
            ev.getConfig()->getPerObjectConfigValue(getFullPath().c_str(),
86
                    "number-local-rngs"), "1", 1);
87

    
88
    //
89
    // read the seeds from ini file
90
    //
91
    const char * seedString = ev.getConfig()->getPerObjectConfigValue(
92
            getFullPath().c_str(), "local-rng-seed");
93

    
94
    //
95
    // setup seeds for each RNG
96
    //
97
    seeds = new unsigned long[nrNumGens];
98
    cStringTokenizer tokenizer(seedString);
99
    const char * token = NULL;
100
    for (unsigned i = 0; i < nrNumGens; i++)
101
    {
102
        if (tokenizer.hasMoreTokens())
103
        {
104
            token = tokenizer.nextToken();
105
            if (strcmp(token, "auto") == 0)
106
            {
107
                token = NULL;
108
            }
109
        }
110

    
111
        EnvirBase* e = dynamic_cast<EnvirBase*> (&ev);
112
        if (e != NULL)
113
        {
114
            if (token)
115
            {
116
                //if the seed is set in the ini for this module, use ini-settings
117
                //with fallback to autogeneration if parsing failes
118
                seeds[i] = ev.getConfig()->parseLong(token, "",
119
                        e->getSeedGenerator()->intRand());
120
            }
121
            else
122
            {
123
                //else use SeedGenerator for automatic seed generation.
124
                seeds[i] = e->getSeedGenerator()->intRand();
125
            }
126
            token = NULL;
127
        }
128
        else
129
        {
130
            throw cRuntimeError(
131
                    "cAsyncModule: Failed to initialize Number Generator, dynamic cast to EnvirBase failed.");
132
        }
133
    }
134

    
135
    //
136
    // generate the required number of RNGs with the corresponding seeds
137
    //
138
    numGen = new cNumberGenerator(nrNumGens,seeds);
139
    delete[] seeds;
140

    
141
}
142

    
143
void cAsyncModule::setMessageMetaData(cMessage* msg)
144
{
145
    msg->setEventDuration(-1);
146
    msg->setSchedulingOrderId(scheduledMessageCount++);
147
    msg->setParentExecutionOrderId(executionOrderId);
148
    msg->setParentStartTime(now);
149
}
150

    
151
int cAsyncModule::scheduleAt(simtime_t t, cMessage *msg)
152
{
153
    setMessageMetaData(msg);
154

    
155
    //
156
    // check current state
157
    //
158
    if (executionState == asynchronous)
159
    {
160
        if (msg==NULL)
161
          throw cRuntimeError("scheduleAt(): message pointer is NULL");
162
        if (t < t_end)
163
                throw cRuntimeError("scheduleAt(): event cannot be scheduled at "
164
                                "%s because this precedes the end of the processing duration "
165
                                "at %s of the scheduling event.",
166
                                t.str().c_str(), t_end.str().c_str());
167

    
168
        if (t == now && currentEventPriority < msg->getSchedulingPriority()) {
169
            throw cRuntimeError("scheduleAt(): priority of scheduled Event larger than scheduling event and scheduling event and equal starting times => scheduling in the past");
170
        }
171
        // insert this message in the FES. When the scheduler arrives at this
172
        // message it will trigger the processing of the associated task
173
        msg->setSentFrom(this, -1, t_end);
174
        msg->setArrival(this, -1, t);
175

    
176
        simulation.msgQueue.insert(msg);
177
        return 0;
178
    }
179
    else // synch execution
180
    {
181
        return cSimpleModule::scheduleAt(t, msg);
182
    }
183
}
184

    
185

    
186
void cAsyncModule::callHandleAsyncMessage(cMessage* msg)
187
{
188
    //
189
    // set execution state
190
    //
191
    executionState = asynchronous;
192

    
193
    //
194
    // set the simtime for this event
195
    //
196
    cThreadPool::setSimTime(msg->getArrivalTime());
197
    // corresponds to setContextModule(mod);
198
    cThreadPool::setContext(this);
199
    cThreadPool::setDefaultOwner(this);
200

    
201
    //
202
    // update meta data
203
    //
204
    prepareHandleMessage(msg);
205

    
206
    //
207
    // call the actual method
208
    //
209
    handleMessage(msg);
210
}
211

    
212

    
213
void cAsyncModule::callHandleMessage(cMessage* msg)
214
{
215
    //
216
    // set execution state
217
    //
218
    executionState = synchronous;
219

    
220
    //
221
    // update meta data
222
    //
223
    prepareHandleMessage(msg);
224

    
225
    //
226
    // call the actual method
227
    //
228
    handleMessage(msg);
229
}
230

    
231

    
232
void cAsyncModule::prepareHandleMessage(cMessage* msg)
233
{
234
    //
235
    // set some internal state
236
    //
237
    t_end = msg->getArrivalTime() + msg->getEventDuration();
238
    now = msg->getArrivalTime();
239
    currentEventPriority = msg->getSchedulingPriority();
240

    
241
    //
242
    // take ownership of the message only after the test above
243
    //
244
    this->take(msg);
245

    
246
    //
247
    // reset message counter
248
    //
249
    scheduledMessageCount = 0;
250

    
251
    executionOrderId = msg->getExecutionOrderId();
252

    
253
}
254

    
255
int cAsyncModule::send(cMessage *msg, int gateid)
256
{
257
    return sendDelayed(msg, 0.0, gateid);
258
}
259

    
260

    
261
int cAsyncModule::send(cMessage *msg, const char *gatename, int sn)
262
{
263
    return sendDelayed(msg, 0.0, gatename, sn);
264
}
265

    
266

    
267
int cAsyncModule::send(cMessage *msg, cGate *outputgate)
268
{
269
    return sendDelayed(msg, 0.0, outputgate);
270
}
271

    
272

    
273
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, int gateid)
274
{
275
    cGate *outgate = gate(gateid);
276
    if (outgate==NULL)
277
        throw cRuntimeError("send()/sendDelayed(): module has no gate #%d", gateid);
278

    
279
    return sendDelayed(msg, delay, outgate);
280
}
281

    
282

    
283
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, const char *gatename, int sn)
284
{
285
    cGate *outgate = gate(gatename, sn);
286
    if (outgate==NULL)
287
       throw cRuntimeError(sn<0 ? "send()/sendDelayed(): module has no gate `%s'":
288
                               "send()/sendDelayed(): module has no gate `%s[%d]'",gatename,sn);
289

    
290
    return sendDelayed(msg, delay, outgate);
291
}
292

    
293

    
294
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, cGate *outputgate)
295
{
296
    setMessageMetaData(msg);
297

    
298
    //
299
    // check current state
300
    //
301
    if (executionState == asynchronous)
302
    {
303
        //
304
        // error checking, omit ownership checks if it breaks
305
        //
306
        if (outputgate==NULL)
307
            throw cRuntimeError("send()/sendDelayed(): gate pointer is NULL");
308
        if (outputgate->getType()=='I')
309
            throw cRuntimeError("send()/sendDelayed(): cannot send via an input gate (`%s')",outputgate->getName());
310
        if (!outputgate->getNextGate())  // NOTE: without this error check, msg would become self-message
311
            throw cRuntimeError("send()/sendDelayed(): gate `%s' not connected",outputgate->getFullName());
312
        if (msg==NULL)
313
            throw cRuntimeError("send()/sendDelayed(): message pointer is NULL");
314
        if (msg->getOwner()!=this)
315
        {
316
            if (this!=simulation.getContext())
317
                throw cRuntimeError("send()/sendDelayed() of module (%s)%s called in the context of "
318
                                        "module (%s)%s: method called from the latter module "
319
                                        "lacks Enter_Method() or Enter_Method_Silent()? "
320
                                        "Also, if message to be sent is passed from that module, "
321
                                        "you'll need to call take(msg) after Enter_Method() as well",
322
                                        getClassName(), getFullPath().c_str(),
323
                                        simulation.getContext()->getClassName(),
324
                                        simulation.getContext()->getFullPath().c_str());
325
            else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage() && msg->getArrivalModuleId()==getId())
326
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
327
                                        "currently scheduled as a self-message for this module",
328
                                        msg->getClassName(), msg->getName());
329
            else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage())
330
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
331
                                        "currently scheduled as a self-message for ANOTHER module",
332
                                        msg->getClassName(), msg->getName());
333
            else if (msg->getOwner()==&simulation.msgQueue)
334
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
335
                                        "currently in scheduled-events, being underway between two modules",
336
                                        msg->getClassName(), msg->getName());
337
            else
338
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, "
339
                                        "it is currently contained/owned by (%s)%s",
340
                                        msg->getClassName(), msg->getName(), msg->getOwner()->getClassName(),
341
                                        msg->getOwner()->getFullPath().c_str());
342
        }
343

    
344
        if (delay < 0.0)
345
            throw cRuntimeError("sendDelayed(): negative delay %s",delay.str().c_str());
346

    
347
        simtime_t arrivalTime = now + delay;
348
        if (arrivalTime < t_end) // TODO: Consider channel delay!
349
            throw cRuntimeError("sendDelayed(): send delay shorter than processing delay %s", delay.str().c_str());
350

    
351
        if (delay == 0 && currentEventPriority < msg->getSchedulingPriority()) {
352
            throw cRuntimeError("sendDelayed(): priority of scheduled Event larger than scheduling event and scheduling event and equal starting times => scheduling in the past");
353
        }
354
        //
355
        // set message parameters and send it
356
        //
357
        msg->setSentFrom(this, outputgate->getId(), arrivalTime);
358
        bool keepit = outputgate->deliver(msg, arrivalTime);
359
        if (!keepit)
360
            delete msg;
361

    
362
        return 0;
363
    }
364
    else // syncExecution
365
    {
366
        return cSimpleModule::sendDelayed(msg, delay, outputgate);
367
    }
368
}
369

    
370

    
371
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cModule *mod, int inputgateid)
372
{
373
    cGate *togate = mod->gate(inputgateid);
374
    if (togate==NULL)
375
        throw cRuntimeError("sendDirect(): module `%s' has no gate #%d",
376
                                mod->getFullPath().c_str(), inputgateid);
377

    
378
    return sendDirect(msg, delay, duration, togate);
379
}
380

    
381

    
382
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cModule *mod, const char *inputgatename, int sn)
383
{
384
    if (!mod)
385
        throw cRuntimeError("sendDirect(): module ptr is NULL");
386
    cGate *togate = mod->gate(inputgatename,sn);
387
    if (togate==NULL)
388
        throw cRuntimeError(sn<0 ? "sendDirect(): module `%s' has no gate `%s'":
389
                                "sendDirect(): module `%s' has no gate `%s[%d]'",
390
                                mod->getFullPath().c_str(), inputgatename, sn);
391
    return sendDirect(msg, delay, duration, togate);
392
}
393

    
394

    
395
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cGate *togate)
396
{
397
    setMessageMetaData(msg);
398

    
399
    //
400
    // check current state
401
    //
402
    if (executionState == asynchronous)
403
    {
404
        //
405
        // error checking
406
        //
407
        // Note: it is permitted to send to an output gate. It is especially useful
408
        // with several submodules sending to a single output gate of their parent module.
409
        if (togate==NULL)
410
                throw cRuntimeError("sendDirect(): destination gate pointer is NULL");
411
        if (togate->getPreviousGate())
412
                throw cRuntimeError("sendDirect(): module must have dedicated gate(s) for receiving via sendDirect()"
413
                                                                " (\"from\" side of dest. gate `%s' should NOT be connected)",togate->getFullPath().c_str());
414
        if (msg==NULL)
415
                throw cRuntimeError("sendDirect(): message pointer is NULL");
416
        if (msg->getOwner()!=this)
417
        {
418
                if (this!=simulation.getContext())
419
                        throw cRuntimeError("sendDirect() of module (%s)%s called in the context of "
420
                                                                        "module (%s)%s: method called from the latter module "
421
                                                                        "lacks Enter_Method() or Enter_Method_Silent()? "
422
                                                                        "Also, if message to be sent is passed from that module, "
423
                                                                        "you'll need to call take(msg) after Enter_Method() as well",
424
                                                                        getClassName(), getFullPath().c_str(),
425
                                                                        simulation.getContext()->getClassName(),
426
                                                                        simulation.getContext()->getFullPath().c_str());
427
                else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage() && msg->getArrivalModuleId()==getId())
428
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
429
                                                                        "currently scheduled as a self-message for this module",
430
                                                                        msg->getClassName(), msg->getName());
431
                else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage())
432
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
433
                                                                        "currently scheduled as a self-message for ANOTHER module",
434
                                                                        msg->getClassName(), msg->getName());
435
                else if (msg->getOwner()==&simulation.msgQueue)
436
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
437
                                                                        "currently in scheduled-events, being underway between two modules",
438
                                                                        msg->getClassName(), msg->getName());
439
                else
440
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, "
441
                                                                        "it is currently contained/owned by (%s)%s",
442
                                                                        msg->getClassName(), msg->getName(), msg->getOwner()->getClassName(),
443
                                                                        msg->getOwner()->getFullPath().c_str());
444
        }
445

    
446
        simtime_t arrivalTime = now + delay;
447
        if (arrivalTime < t_end) // TODO: Consider channel delay!
448
            throw cRuntimeError("sendDirect(): send delay shorter than processing delay %s",delay.str().c_str());
449

    
450
        if (delay == 0 && currentEventPriority < msg->getSchedulingPriority()) {
451
            throw cRuntimeError("sendDirect(): priority of scheduled Event larger than scheduling event and scheduling event and equal starting times => scheduling in the past");
452
        }
453

    
454
        // set message parameters and send it
455
        msg->setSentFrom(this, -1, now);
456

    
457
        bool keepit = togate->deliver(msg, arrivalTime);
458
        if (!keepit)
459
                delete msg;
460
        return 0;
461
    }
462
    else  // sync execution
463
    {
464
            return cSimpleModule::sendDirect(msg, delay, duration, togate);
465
    }
466
}