Project

General

Profile

Statistics
| Branch: | Revision:

root / src / sim / casyncmodule.cc @ 6b036b78

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