Statistics
| Branch: | Revision:

root / src / sim / casyncmodule.cc @ e26d3d25

History | View | Annotate | Download (14.6 KB)

1 01873262 Georg Kunz
//=========================================================================
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 <stdlib.h>
24
25
#include "casyncmodule.h"
26
#include "cthreadpool.h"
27
#include "cconfiguration.h"
28
#include "cconfigoption.h"
29
30
31
Register_PerRunConfigOption(CFGID_ASYNCMODULE_PARZERODUR, "parallelize-zero-duration-events", CFG_BOOL, "false", "Parallelize Events with zero duration");
32
33
34
cAsyncModule::cAsyncModule(const char *name, cModule *parent, unsigned stacksize) :
35
                t_end(0.0)
36
{
37
    AO_store(&execState, 0);
38
39
    //
40
        // how many local random number generators do we need? This should become a
41
        // special parameter of every asyncmodule. Not yet implemented.
42
        //
43
        unsigned nrNumGens = 1;
44
        /*
45
         cPar *p = (cPar*)paramv.get("number-local-rngs");
46
         if (p)
47
         nrNumGens = *p;
48

49
         std::cout << "number-local-rngs in " << fullName() << ": " << nrNumGens << std::endl;
50
         */
51
        numGen = new cNumberGenerator(nrNumGens);
52
53
        //
54
        // find out if events with 0 durations also be parallelized?
55
        //
56
        parZeroDur = ev.getConfig()->getAsBool(CFGID_ASYNCMODULE_PARZERODUR);
57
58
        //
59
        // init state flag to non-busy since no thread is active yet
60
        //
61
        AO_store(&busy, 0);
62
}
63
64
65
cAsyncModule::~cAsyncModule()
66
{
67
  delete numGen;
68
}
69
70
71
int cAsyncModule::scheduleAt(simtime_t t, cMessage *msg)
72
{
73
    //
74
    // check current state
75
    //
76
    AO_t currentState = AO_load_acquire(&execState);
77
    if (currentState == asyncExecution)
78
    {
79
        if (msg==NULL)
80
          throw cRuntimeError("scheduleAt(): message pointer is NULL");
81
        if (t < t_end)
82
                throw cRuntimeError("scheduleAt(): event cannot be scheduled at "
83
                                "%s because this precedes the end of the processing duration "
84
                                "at %s of the scheduling event.",
85
                                t.str().c_str(), t_end.str().c_str());
86
87
        // insert this message in the FES. When the scheduler arrives at this
88
        // message it will trigger the processing of the associated task
89
        msg->setSentFrom(this, -1, t_end);
90
        msg->setArrival(this, -1, t);
91
        simulation.msgQueue.insert(msg);
92
        return 0;
93
    }
94
    else // synch execution
95
    {
96
        return cSimpleModule::scheduleAt(t, msg);
97
    }
98
}
99
100
101
void cAsyncModule::callHandleAsyncMessage(cMessage* msg)
102
{
103
    //
104
    // check if an event is being processed currently
105
    //
106
    AO_t oldState, newState;
107
    AO_store_write(&newState, asyncExecution);
108
    AO_store_write(&oldState, idleExecution);
109
110
    int res = AO_compare_and_swap_full(&execState, oldState, newState);
111
    if (res == 0)
112
    {
113
        throw cRuntimeError(this, "Race condition detected: Cannot process "
114
                                      "asynchronous event - already processing "
115
                                      "event in module %s", this->getName());
116
    }
117
118
    //
119
    // set some internal state
120
    //
121
    t_end = msg->getArrivalTime() + msg->getEventDuration();
122
123
    //
124
    // set the simtime for this event
125
    //
126
    cThreadPool::setSimTime(msg->getArrivalTime());
127
128
    // corresponds to setContextModule(mod);
129
    cThreadPool::setContext(this);
130
    cThreadPool::setDefaultOwner(this);
131
132
    // take ownership of the message only after the test above
133
    this->take(msg);
134
135
    //
136
    // call the actual method
137
    //
138
    handleMessage(msg);
139
140
    AO_store_release(&execState, idleExecution);
141
142
}
143
144
145
void cAsyncModule::callHandleMessage(cMessage* msg)
146
{
147
    //
148
    // check if an event is being processed currently
149
    //
150
    AO_t oldState, newState;
151
    AO_store_write(&newState, syncExecution);
152
    AO_store_write(&oldState, idleExecution);
153
154
    int res = AO_compare_and_swap_full(&execState, oldState, newState);
155
    if (res == 0)
156
    {
157
        throw cRuntimeError(this, "Race condition detected: Cannot process "
158
                                      "synchronous event - already processing "
159
                                      "event in module %s", this->getName());
160
    }
161
162
    t_end = msg->getArrivalTime() + msg->getEventDuration();
163
164
    //
165
    // take ownership of the message only after the test above
166
    //
167
    this->take(msg);
168
169
    //
170
    // call the actual method
171
    //
172
    handleMessage(msg);
173
174
    AO_store_release(&execState, idleExecution);
175
}
176
177
178
int cAsyncModule::send(cMessage *msg, int gateid)
179
{
180
    return sendDelayed(msg, 0.0, gateid);
181
}
182
183
184
int cAsyncModule::send(cMessage *msg, const char *gatename, int sn)
185
{
186
    return sendDelayed(msg, 0.0, gatename, sn);
187
}
188
189
190
int cAsyncModule::send(cMessage *msg, cGate *outputgate)
191
{
192
    return sendDelayed(msg, 0.0, outputgate);
193
}
194
195
196
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, int gateid)
197
{
198
    cGate *outgate = gate(gateid);
199
    if (outgate==NULL)
200
        throw cRuntimeError("send()/sendDelayed(): module has no gate #%d", gateid);
201
202
    return sendDelayed(msg, delay, outgate);
203
}
204
205
206
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, const char *gatename, int sn)
207
{
208
    cGate *outgate = gate(gatename, sn);
209
    if (outgate==NULL)
210
       throw cRuntimeError(sn<0 ? "send()/sendDelayed(): module has no gate `%s'":
211
                               "send()/sendDelayed(): module has no gate `%s[%d]'",gatename,sn);
212
213
    return sendDelayed(msg, delay, outgate);
214
}
215
216
217
int cAsyncModule::sendDelayed(cMessage *msg, simtime_t delay, cGate *outputgate)
218
{
219
    //
220
    // check current state
221
    //
222
    AO_t currentState = AO_load_acquire(&execState);
223
    if (currentState == asyncExecution)
224
    {
225
        //
226
        // error checking, omit ownership checks if it breaks
227
        //
228
        if (outputgate==NULL)
229
            throw cRuntimeError("send()/sendDelayed(): gate pointer is NULL");
230
        if (outputgate->getType()=='I')
231
            throw cRuntimeError("send()/sendDelayed(): cannot send via an input gate (`%s')",outputgate->getName());
232
        if (!outputgate->getNextGate())  // NOTE: without this error check, msg would become self-message
233
            throw cRuntimeError("send()/sendDelayed(): gate `%s' not connected",outputgate->getFullName());
234
        if (msg==NULL)
235
            throw cRuntimeError("send()/sendDelayed(): message pointer is NULL");
236
        if (msg->getOwner()!=this)
237
        {
238
            if (this!=simulation.getContext())
239
                throw cRuntimeError("send()/sendDelayed() of module (%s)%s called in the context of "
240
                                        "module (%s)%s: method called from the latter module "
241
                                        "lacks Enter_Method() or Enter_Method_Silent()? "
242
                                        "Also, if message to be sent is passed from that module, "
243
                                        "you'll need to call take(msg) after Enter_Method() as well",
244
                                        getClassName(), getFullPath().c_str(),
245
                                        simulation.getContext()->getClassName(),
246
                                        simulation.getContext()->getFullPath().c_str());
247
            else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage() && msg->getArrivalModuleId()==getId())
248
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
249
                                        "currently scheduled as a self-message for this module",
250
                                        msg->getClassName(), msg->getName());
251
            else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage())
252
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
253
                                        "currently scheduled as a self-message for ANOTHER module",
254
                                        msg->getClassName(), msg->getName());
255
            else if (msg->getOwner()==&simulation.msgQueue)
256
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, it is "
257
                                        "currently in scheduled-events, being underway between two modules",
258
                                        msg->getClassName(), msg->getName());
259
            else
260
                throw cRuntimeError("send()/sendDelayed(): cannot send message (%s)%s, "
261
                                        "it is currently contained/owned by (%s)%s",
262
                                        msg->getClassName(), msg->getName(), msg->getOwner()->getClassName(),
263
                                        msg->getOwner()->getFullPath().c_str());
264
        }
265
266
        simtime_t t = simTime();
267
        if (delay<0.0)
268
            throw cRuntimeError("sendDelayed(): negative delay %s",delay.str().c_str());
269
        if (t+delay<t_end) // TODO: Consider channel delay!
270
            throw cRuntimeError("sendDelayed(): send delay shorter than processing delay %s", delay.str().c_str());
271
272
        //
273
        // set message parameters and send it
274
        //
275
        msg->setSentFrom(this, outputgate->getId(), t+delay);
276
        bool keepit = outputgate->deliver(msg, t+delay);
277
        if (!keepit)
278
            delete msg;
279
280
        return 0;
281
    }
282
    else // syncExecution
283
    {
284
        return cSimpleModule::sendDelayed(msg, delay, outputgate);
285
    }
286
}
287
288
289
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cModule *mod, int inputgateid)
290
{
291
    cGate *togate = mod->gate(inputgateid);
292
    if (togate==NULL)
293
        throw cRuntimeError("sendDirect(): module `%s' has no gate #%d",
294
                                mod->getFullPath().c_str(), inputgateid);
295
296
    return sendDirect(msg, delay, duration, togate);
297
}
298
299
300
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cModule *mod, const char *inputgatename, int sn)
301
{
302
    if (!mod)
303
        throw cRuntimeError("sendDirect(): module ptr is NULL");
304
    cGate *togate = mod->gate(inputgatename,sn);
305
    if (togate==NULL)
306
        throw cRuntimeError(sn<0 ? "sendDirect(): module `%s' has no gate `%s'":
307
                                "sendDirect(): module `%s' has no gate `%s[%d]'",
308
                                mod->getFullPath().c_str(), inputgatename, sn);
309
    return sendDirect(msg, delay, duration, togate);
310
}
311
312
313
int cAsyncModule::sendDirect(cMessage *msg, simtime_t delay, simtime_t duration, cGate *togate)
314
{
315
    //
316
    // check current state
317
    //
318
    AO_t currentState = AO_load_acquire(&execState);
319
    if (currentState == asyncExecution)
320
    {
321
        //
322
        // error checking
323
        //
324
        // Note: it is permitted to send to an output gate. It is especially useful
325
        // with several submodules sending to a single output gate of their parent module.
326
        if (togate==NULL)
327
                throw cRuntimeError("sendDirect(): destination gate pointer is NULL");
328
        if (togate->getPreviousGate())
329
                throw cRuntimeError("sendDirect(): module must have dedicated gate(s) for receiving via sendDirect()"
330
                                                                " (\"from\" side of dest. gate `%s' should NOT be connected)",togate->getFullPath().c_str());
331
        if (msg==NULL)
332
                throw cRuntimeError("sendDirect(): message pointer is NULL");
333
        if (msg->getOwner()!=this)
334
        {
335
                if (this!=simulation.getContext())
336
                        throw cRuntimeError("sendDirect() of module (%s)%s called in the context of "
337
                                                                        "module (%s)%s: method called from the latter module "
338
                                                                        "lacks Enter_Method() or Enter_Method_Silent()? "
339
                                                                        "Also, if message to be sent is passed from that module, "
340
                                                                        "you'll need to call take(msg) after Enter_Method() as well",
341
                                                                        getClassName(), getFullPath().c_str(),
342
                                                                        simulation.getContext()->getClassName(),
343
                                                                        simulation.getContext()->getFullPath().c_str());
344
                else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage() && msg->getArrivalModuleId()==getId())
345
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
346
                                                                        "currently scheduled as a self-message for this module",
347
                                                                        msg->getClassName(), msg->getName());
348
                else if (msg->getOwner()==&simulation.msgQueue && msg->isSelfMessage())
349
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
350
                                                                        "currently scheduled as a self-message for ANOTHER module",
351
                                                                        msg->getClassName(), msg->getName());
352
                else if (msg->getOwner()==&simulation.msgQueue)
353
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, it is "
354
                                                                        "currently in scheduled-events, being underway between two modules",
355
                                                                        msg->getClassName(), msg->getName());
356
                else
357
                        throw cRuntimeError("sendDirect(): cannot send message (%s)%s, "
358
                                                                        "it is currently contained/owned by (%s)%s",
359
                                                                        msg->getClassName(), msg->getName(), msg->getOwner()->getClassName(),
360
                                                                        msg->getOwner()->getFullPath().c_str());
361
        }
362
363
        // set message parameters and send it
364
        simtime_t time = simTime();
365
        if (time + delay < t_end) // TODO: Consider channel delay!
366
            throw cRuntimeError("sendDelayed(): send delay shorter than processing delay %s",delay.str().c_str());
367
368
        msg->setSentFrom(this, -1, time);
369
370
        bool keepit = togate->deliver(msg, time + delay);
371
        if (!keepit)
372
                delete msg;
373
        return 0;
374
    }
375
    else  // sync execution
376
    {
377
            return cSimpleModule::sendDirect(msg, delay, duration, togate);
378
    }
379
}