| 1 |
/********************************************************************* |
| 2 |
* |
| 3 |
* AUTHORIZATION TO USE AND DISTRIBUTE |
| 4 |
* |
| 5 |
* Redistribution and use in source and binary forms, with or without |
| 6 |
* modification, are permitted provided that: |
| 7 |
* |
| 8 |
* (1) source code distributions retain this paragraph in its entirety, |
| 9 |
* |
| 10 |
* (2) distributions including binary code include this paragraph in |
| 11 |
* its entirety in the documentation or other materials provided |
| 12 |
* with the distribution, and |
| 13 |
* |
| 14 |
* (3) all advertising materials mentioning features or use of this |
| 15 |
* software display the following acknowledgment: |
| 16 |
* |
| 17 |
* "This product includes software written and developed |
| 18 |
* by Brian Adamson and Joe Macker of the Naval Research |
| 19 |
* Laboratory (NRL)." |
| 20 |
* |
| 21 |
* The name of NRL, the name(s) of NRL employee(s), or any entity |
| 22 |
* of the United States Government may not be used to endorse or |
| 23 |
* promote products derived from this software, nor does the |
| 24 |
* inclusion of the NRL written and developed software directly or |
| 25 |
* indirectly suggest NRL or United States Government endorsement |
| 26 |
* of this product. |
| 27 |
* |
| 28 |
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR |
| 29 |
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED |
| 30 |
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. |
| 31 |
********************************************************************/ |
| 32 |
|
| 33 |
#ifndef _PROTO_DISPATCHER |
| 34 |
#define _PROTO_DISPATCHER |
| 35 |
|
| 36 |
#include "protoTimer.h" |
| 37 |
#include "protoSocket.h" |
| 38 |
#include "protoChannel.h" |
| 39 |
#include "protoEvent.h" |
| 40 |
#include "protoQueue.h" // for keeping track of our "streams" (channels, sockets, generic) |
| 41 |
|
| 42 |
#ifdef WIN32 |
| 43 |
|
| 44 |
#ifndef _WIN32_WCE |
| 45 |
#include <process.h> // for _beginthreadex/_endthreadex |
| 46 |
#endif // !_WIN32_WCE |
| 47 |
|
| 48 |
#define USE_WAITABLE_TIMER 1 |
| 49 |
|
| 50 |
#else // UNIX |
| 51 |
#include <pthread.h> |
| 52 |
#include <unistd.h> // for read(), etc |
| 53 |
|
| 54 |
// There are some compile-time options here for |
| 55 |
// the async i/o mechanism ProtoDispatcher uses |
| 56 |
// (e.g., "select()", "kqueue()", "epoll", etc) |
| 57 |
#if defined(MACOSX) |
| 58 |
// Makefile must pick either USE_KQUEUE or USE_SELECT |
| 59 |
// or we default to USE_SELECT (TBD) |
| 60 |
#if (!defined(USE_KQUEUE) && !defined(USE_SELECT)) |
| 61 |
#warning "Neither USE_SELECT or USE_KQUEUE defined, setting USE_SELECT by default" |
| 62 |
#define USE_SELECT 1 |
| 63 |
#endif // MACOSX |
| 64 |
|
| 65 |
#include <sys/types.h> |
| 66 |
#include <sys/event.h> |
| 67 |
#include <sys/time.h> |
| 68 |
|
| 69 |
#elif defined(LINUX) |
| 70 |
// Makefile must pick USE_SELECT or USE_EPOLL or we |
| 71 |
// default to USE_SELECT (TBD) |
| 72 |
#if (!defined(USE_SELECT) && !defined(USE_EPOLL)) |
| 73 |
#warning "Neither USE_SELECT or USE_EPOLL defined, setting USE_SELECT" |
| 74 |
#define USE_SELECT 1 |
| 75 |
#endif // !defined(USE_SELECT) & !defined(USE_EPOLL) |
| 76 |
// Makefile must pick either USE_EPOLL or USE_SELECT |
| 77 |
#ifdef USE_EPOLL |
| 78 |
#include <sys/epoll.h> |
| 79 |
#ifdef USE_SELECT |
| 80 |
#error "Must define either USE_EPOLL or USE_SELECT, not both!" |
| 81 |
#endif // USE_SELECT |
| 82 |
#endif // USE_EPOLL |
| 83 |
#ifdef USE_TIMERFD |
| 84 |
#include <sys/timerfd.h> |
| 85 |
#endif // USE_TIMERFD |
| 86 |
#ifdef USE_EVENTFD |
| 87 |
#include <sys/eventfd.h> |
| 88 |
#endif // USE_EVENTFD |
| 89 |
|
| 90 |
#else // "other" UNIX |
| 91 |
#define USE_SELECT 1 // default Unix async i/o and timing mechanism |
| 92 |
#endif // if/else MACOSX / LINUX / OTHER |
| 93 |
|
| 94 |
#endif // if/else WIN32/UNIX |
| 95 |
|
| 96 |
#ifndef WIN32 |
| 97 |
// This solves a conflict with pcap.h |
| 98 |
#ifdef SOCKET |
| 99 |
#undef SOCKET |
| 100 |
#endif |
| 101 |
#endif // !WIN32 |
| 102 |
|
| 103 |
/** |
| 104 |
* @class ProtoDispatcher |
| 105 |
* |
| 106 |
* @brief This class provides a core around which Unix and Win32 applications |
| 107 |
* using Protolib can be implemented. |
| 108 |
* |
| 109 |
* It's "Run()" method provides a "main loop" which uses |
| 110 |
* the "select()" system call on Unix and the |
| 111 |
* similar "MsgWaitForMultipleObjectsEx()" system call on Win32. It |
| 112 |
* is planned to eventually provide some built-in support for threading |
| 113 |
* in the future (e.g. the ProtoDispatcher::Run() method might execute |
| 114 |
* in a thread, dispatching events to a parent thread). |
| 115 |
*/ |
| 116 |
|
| 117 |
/*********************** |
| 118 |
ProtoDispatcher Update Notes |
| 119 |
|
| 120 |
ProtoDispatcher is going to be updated to use epoll() and kevent() |
| 121 |
APIs instead of select() for supporting Linux and BSD operating systems. |
| 122 |
Note select() usage will still be supported, but the code is going to |
| 123 |
be streamlined significantly as part of this update. Since there are |
| 124 |
going to be added wait/dispatch paradigms put in place, the following |
| 125 |
notes summarize these (i.e. "select()", "epoll()", "kevent()", and |
| 126 |
"WaitForMultipleObjectsEx()" |
| 127 |
|
| 128 |
|
| 129 |
select() - Each call to select() requires populated file descriptor sets |
| 130 |
for "input", "output", and "exceptions". These "fdsets" need |
| 131 |
to set prior to each call to select(). ProtoDispatcher can keep |
| 132 |
reference input, output, and exception "fdsets" that are modified |
| 133 |
with calls to Update{Channel | Socket | Generic}Notification() and |
| 134 |
then FD_COPY() with each call to select(). |
| 135 |
A threaded ProtoDispatcher can be "broken" from the "select()" based |
| 136 |
wait state using its built-in "break pipe" (self-pipe set up for this) |
| 137 |
|
| 138 |
Summary of ProtoDispatcher state/ops needed: |
| 139 |
a) Keep list of active "streams" |
| 140 |
b) for time efficiency, keep reference fdsets for FD_COPY() to select() |
| 141 |
c) on dispatch, iterate through active "streams" and check FD_ISSET() |
| 142 |
|
| 143 |
epoll() - The "epoll_ctl()" function is used to set/change/unset the list of |
| 144 |
descriptors that epoll() monitors. Then epoll_wait() is a blocking |
| 145 |
call that is used to get notification of events. For Linux, we |
| 146 |
can use the timerfd, signalfd, and eventfd functions to set up |
| 147 |
waitable descriptors for timing, signals, and notional "events". |
| 148 |
We can use eventfd() instead of the "break pipe" on Linux. |
| 149 |
|
| 150 |
Summary of ProtoDispatcher state/ops needed: |
| 151 |
a) Keep list of active "streams" |
| 152 |
b) changes to stream status, handled directly with epoll_ctl, no extra state needed |
| 153 |
c) on dispatch, dereference associated "stream" using epoll_event.data.ptr |
| 154 |
|
| 155 |
kevent() - A "changelist" is passed to each call of kevent() to optionally |
| 156 |
modify the set of things monitored by a given kqueue(). The same |
| 157 |
"struct kevent" array can be used as the "changelist" and the |
| 158 |
"eventlist" to pass in changes and get pending events with one |
| 159 |
call. Note that EVFILT_USER can be used to set up a sort |
| 160 |
of user-defined "event" that a kevent() call in another thread |
| 161 |
can "set" for the given kqueue descriptor. This can be used |
| 162 |
instead of the "break pipe". |
| 163 |
|
| 164 |
Summary of ProtoDispatcher state/ops needed: |
| 165 |
a) Keep list of active "streams" |
| 166 |
b) keep array of "struct kevent" to accumulate stream status changes |
| 167 |
c) on dispatch, dereference associated "stream" using epoll_event.data.ptr |
| 168 |
|
| 169 |
WaitForMultipleObjectsEx() - An array of handles is passed in. When one of |
| 170 |
handles is "ready" or "set", the function returns |
| 171 |
giving the value "index + WAIT_OBJECT0" for given |
| 172 |
the array. ProtoDispatcher can keep a dual arrays |
| 173 |
that are set/modified/unset with calls to |
| 174 |
Update{Channel | Socket | Generic}Notification() |
| 175 |
where one array is the array of handles required |
| 176 |
and a corresponding array has pointers to the |
| 177 |
corresponding ProtoDispatcher::Stream object. |
| 178 |
For objects that have both input and/or output |
| 179 |
handles, separate "index" and "outdex" values are |
| 180 |
kept. |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
THE PLAN: |
| 185 |
Step 1: Streamline current Unix/Win32 code that uses select()/WaitForMultipleObjectEx() |
| 186 |
so we can cleanly incorporate the alternative epoll() / kevent() implementation |
| 187 |
(e.g. make "thread break" consistent/modular, consolidate Channel/Socket/Generic stream |
| 188 |
into a single data structure that is randomly accessible and rapidly |
| 189 |
iterable (e.g. ProtoSortedTree). |
| 190 |
|
| 191 |
Step 2: Extend Linux version to formally use timerfd, eventfd, and signalfd APIs with select()? |
| 192 |
|
| 193 |
Step 3: Probably tackle "kevent()" implementation next? |
| 194 |
|
| 195 |
Step 4: Finally, do "epoll()" implementation |
| 196 |
|
| 197 |
|
| 198 |
************************/ |
| 199 |
|
| 200 |
|
| 201 |
/// Asynchronous event dispatcher and timer scheduler class |
| 202 |
class ProtoDispatcher : public ProtoTimerMgr, |
| 203 |
public ProtoSocket::Notifier, |
| 204 |
public ProtoChannel::Notifier, |
| 205 |
public ProtoEvent::Notifier |
| 206 |
{ |
| 207 |
public: |
| 208 |
// Construction |
| 209 |
ProtoDispatcher(); |
| 210 |
virtual ~ProtoDispatcher(); |
| 211 |
void Destroy(); |
| 212 |
|
| 213 |
// ProtoTimerMgr overrides |
| 214 |
// Note the underlying ProtoTimerMgr will call ProtoDispatcher::UpdateSystemTimer() |
| 215 |
// as needed which will will "wake up" (via ProtoDispatcher::SignalThread()) the |
| 216 |
// dispatcher instance as needed |
| 217 |
void ActivateTimer(ProtoTimer& theTimer) |
| 218 |
{ |
| 219 |
// TBD - should we SignalThread() the thread to wake it up? |
| 220 |
SuspendThread(); |
| 221 |
ProtoTimerMgr::ActivateTimer(theTimer); |
| 222 |
ResumeThread(); |
| 223 |
} |
| 224 |
void DeactivateTimer(ProtoTimer& theTimer) |
| 225 |
{ |
| 226 |
SuspendThread(); |
| 227 |
ProtoTimerMgr::DeactivateTimer(theTimer); |
| 228 |
ResumeThread(); |
| 229 |
} |
| 230 |
|
| 231 |
// Methods to manage generic input/output streams (pipes, files, devices, etc) |
| 232 |
typedef ProtoChannel::Handle Descriptor; // , UNIX "int" descriptors, Win32 "HANDLE" type |
| 233 |
|
| 234 |
static const Descriptor INVALID_DESCRIPTOR; |
| 235 |
enum Event {EVENT_INPUT, EVENT_OUTPUT}; |
| 236 |
typedef void (Callback)(ProtoDispatcher::Descriptor descriptor, |
| 237 |
ProtoDispatcher::Event theEvent, |
| 238 |
const void* userData); |
| 239 |
bool InstallGenericInput(ProtoDispatcher::Descriptor descriptor, |
| 240 |
ProtoDispatcher::Callback* callback, |
| 241 |
const void* clientData); |
| 242 |
void RemoveGenericInput(Descriptor descriptor); |
| 243 |
bool InstallGenericOutput(ProtoDispatcher::Descriptor descriptor, |
| 244 |
ProtoDispatcher::Callback* callback, |
| 245 |
const void* clientData); |
| 246 |
void RemoveGenericOutput(Descriptor descriptor); |
| 247 |
|
| 248 |
// Methods to set up and explicitly control ProtoDispatcher operation |
| 249 |
/// Are there any pending timeouts/descriptors? |
| 250 |
bool IsPending() |
| 251 |
{ |
| 252 |
return (IsThreaded() || |
| 253 |
ProtoTimerMgr::IsActive() || |
| 254 |
!stream_table.IsEmpty()); |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* This can safely be called on a dispatcher _before_ |
| 259 |
* the "StartThread()" or "Run()" method is called without |
| 260 |
* affecting the current process priority |
| 261 |
*/ |
| 262 |
void SetPriorityBoost(bool state) |
| 263 |
{priority_boost = state;} |
| 264 |
|
| 265 |
/** |
| 266 |
* This one will affect the current process priority if |
| 267 |
* "StartThread()" has not already been called. |
| 268 |
*/ |
| 269 |
bool BoostPriority(); |
| 270 |
|
| 271 |
/** |
| 272 |
* Block until next event (timer, socket, other, occurs) |
| 273 |
* (Note this will block forever if !IsPending()) |
| 274 |
*/ |
| 275 |
void Wait(); |
| 276 |
|
| 277 |
/// Dispatch round of events |
| 278 |
void Dispatch(); |
| 279 |
|
| 280 |
/// OR this "main loop" can be used. |
| 281 |
int Run(bool oneShot = false); |
| 282 |
void Stop(int exitCode = 0); |
| 283 |
|
| 284 |
bool IsRunning() const // TBD - deprecate IsRunning() method? |
| 285 |
{return run;} |
| 286 |
|
| 287 |
/** |
| 288 |
* Controls whether time of day is polled for ultra-precise timing |
| 289 |
* If "precise timing" is set to "true", the time of day is polled |
| 290 |
* to achieve precise timer timeouts. However, this can consume |
| 291 |
* considerable CPU resources. The default state is "false". |
| 292 |
*/ |
| 293 |
void SetPreciseTiming(bool state) |
| 294 |
{precise_timing = state;} |
| 295 |
// For debugging purposes |
| 296 |
void SetUserData(const void* userData) |
| 297 |
{user_data = userData;} |
| 298 |
const void* GetUserData() |
| 299 |
{return user_data;} |
| 300 |
|
| 301 |
|
| 302 |
#ifdef WIN32 |
| 303 |
typedef CRITICAL_SECTION Mutex; |
| 304 |
static void Init(Mutex& m) {InitializeCriticalSection(&m);} |
| 305 |
static void Destroy(Mutex& m) {DeleteCriticalSection(&m);} |
| 306 |
static void Lock(Mutex& m) {EnterCriticalSection(&m);} |
| 307 |
static void Unlock(Mutex& m) {LeaveCriticalSection(&m);} |
| 308 |
#else |
| 309 |
typedef pthread_mutex_t Mutex; |
| 310 |
static void Init(Mutex& m) {pthread_mutex_init(&m, NULL);} |
| 311 |
static void Destroy(Mutex& m) {pthread_mutex_destroy(&m);} |
| 312 |
static void Lock(Mutex& m) {pthread_mutex_lock(&m);} |
| 313 |
static void Unlock(Mutex& m) {pthread_mutex_unlock(&m);} |
| 314 |
#endif // if/else WIN32/UNIX |
| 315 |
/** |
| 316 |
* @class Controller |
| 317 |
* |
| 318 |
* @brief Handles dispatching for the ProtoDispatcher |
| 319 |
* The ProtoDispatcher::Controller helper class allows for |
| 320 |
* thread-safe synchronization when using the "StartThread()" |
| 321 |
* mode. |
| 322 |
*/ |
| 323 |
class Controller |
| 324 |
{ |
| 325 |
public: |
| 326 |
virtual ~Controller(); |
| 327 |
|
| 328 |
protected: |
| 329 |
void OnDispatch(); // should be called by Controller thread in response to SignalDispatchReady() cue |
| 330 |
Controller(ProtoDispatcher& theDispatcher); |
| 331 |
|
| 332 |
private: |
| 333 |
friend class ProtoDispatcher; |
| 334 |
bool DoDispatch(); /// only called by ProtoDispatcher |
| 335 |
virtual bool SignalDispatchReady() = 0; // cue to controller to make "OnDispatch() call |
| 336 |
void OnThreadStop() |
| 337 |
{ |
| 338 |
if (use_lock_a) |
| 339 |
ProtoDispatcher::Unlock(lock_a); |
| 340 |
else |
| 341 |
ProtoDispatcher::Unlock(lock_b); |
| 342 |
} |
| 343 |
|
| 344 |
ProtoDispatcher& dispatcher; |
| 345 |
Mutex lock_a; |
| 346 |
Mutex lock_b; |
| 347 |
bool use_lock_a; |
| 348 |
}; // end class ProtoDispatcher::Controller() |
| 349 |
friend class Controller; |
| 350 |
|
| 351 |
#ifdef WIN32 |
| 352 |
typedef DWORD ThreadId; |
| 353 |
#else |
| 354 |
typedef pthread_t ThreadId; |
| 355 |
#endif // if/else WIN32 |
| 356 |
|
| 357 |
// OR the dispatcher can be run in a thread n(w/ optional Controller) |
| 358 |
bool StartThread(bool priorityBoost = false, |
| 359 |
ProtoDispatcher::Controller* theController = NULL, |
| 360 |
ThreadId threadId = (ThreadId)NULL); |
| 361 |
bool IsThreaded() {return ((ThreadId)(NULL) != thread_id);} |
| 362 |
|
| 363 |
/** |
| 364 |
* (NOTE: If dispatcher instance is threaded, you MUST successfully call |
| 365 |
* "SuspendThread()" before calling _any_ dispatcher methods or |
| 366 |
* manipulating any objects (ProtoTimers, ProtoSockets, etc) |
| 367 |
* which affect dispatcher operation!!!! |
| 368 |
* (Call "ResumeThread()" to allow the dispatcher to continue) |
| 369 |
* This can be used to create thread-safe protocols/applications |
| 370 |
* which use a ProtoDispatcher for async timing and I/O) |
| 371 |
*/ |
| 372 |
bool SuspendThread(); |
| 373 |
void ResumeThread(); |
| 374 |
|
| 375 |
// The "prompting" mechanism here is a way to cause a sleeping |
| 376 |
// thread to wakeup and execute a bit of code as set by the |
| 377 |
// "PromptCallback" |
| 378 |
// (TBD) refine this prompting mechanism a little bit |
| 379 |
// for example, some sort of waiting mechanism |
| 380 |
// (e.g., the child could prompt its parent? add "promptData" option to PromptThread()? |
| 381 |
// should be added to know when the work has been done. |
| 382 |
// For example, a waitable descriptor. This way a "parent" |
| 383 |
// ProtoApp or ProtoDispatcher could create/start a pool of |
| 384 |
// waiting worker threads, assign them jobs, and reap the results |
| 385 |
// upon completion ... |
| 386 |
typedef void (PromptCallback)(const void* clientData); |
| 387 |
/** |
| 388 |
* Use this to set a PromptCallback function |
| 389 |
* (should do this _before_ StartThread() is invoked |
| 390 |
*/ |
| 391 |
void SetPromptCallback(PromptCallback* theCallback, const void* clientData = NULL) |
| 392 |
{ |
| 393 |
prompt_callback = theCallback; |
| 394 |
prompt_client_data = clientData; |
| 395 |
} |
| 396 |
|
| 397 |
/// Call this to force call of PromptCallback in thread's context |
| 398 |
bool PromptThread(); |
| 399 |
|
| 400 |
|
| 401 |
#ifdef WIN32 |
| 402 |
/// WIN32 apps can call this to create a msg window if desired |
| 403 |
bool Win32Init(); |
| 404 |
void Win32Cleanup(); |
| 405 |
#endif // WIN32 |
| 406 |
|
| 407 |
public: |
| 408 |
bool SignalThread(); |
| 409 |
void UnsignalThread(); |
| 410 |
private: |
| 411 |
bool WasSignaled(); |
| 412 |
/// Associated ProtoTimerMgrs will use this as needed |
| 413 |
bool UpdateSystemTimer(ProtoTimer::Command /*command*/, |
| 414 |
double /* delay*/) |
| 415 |
{ |
| 416 |
// ProtoDispatcher::Dispatch() queries ProtoTimerMgr::GetTimeRemaining() instead |
| 417 |
// The signal/unsignal here just wakes up the thread so this happens |
| 418 |
SignalThread(); |
| 419 |
UnsignalThread(); |
| 420 |
return true; |
| 421 |
} |
| 422 |
// Associated ProtoSockets will use this as needed |
| 423 |
bool UpdateSocketNotification(ProtoSocket& theSocket, |
| 424 |
int notifyFlags); |
| 425 |
|
| 426 |
// Associated ProtoChannels will use this as needed |
| 427 |
bool UpdateChannelNotification(ProtoChannel& theChannel, |
| 428 |
int notifyFlags); |
| 429 |
|
| 430 |
// Associated ProtoEvents will use this as needed |
| 431 |
bool UpdateEventNotification(ProtoEvent& theEvent, |
| 432 |
int notifyFlags); |
| 433 |
|
| 434 |
// Thread/Mutex stuff (TBD - make this its own class ???) |
| 435 |
#ifdef WIN32 |
| 436 |
typedef DWORD WaitStatus; |
| 437 |
//typedef DWORD ThreadId; |
| 438 |
ThreadId GetCurrentThread() {return ::GetCurrentThreadId();} |
| 439 |
#ifdef _WIN32_WCE |
| 440 |
typedef DWORD ExitStatus; |
| 441 |
static void DoThreadExit(ExitStatus exitStatus) {ExitThread(exitStatus);} |
| 442 |
#else |
| 443 |
typedef unsigned int ExitStatus; |
| 444 |
static void DoThreadExit(ExitStatus exitStatus) {_endthreadex(exitStatus);} |
| 445 |
#endif // if/else _WIN32_WCE |
| 446 |
ExitStatus GetExitStatus() |
| 447 |
{return exit_status;} |
| 448 |
#else // Unix |
| 449 |
typedef int WaitStatus; |
| 450 |
//typedef pthread_t ThreadId; |
| 451 |
static ThreadId GetCurrentThread() {return pthread_self();} |
| 452 |
typedef void* ExitStatus; |
| 453 |
ExitStatus GetExitStatus() // note pthread uses a _pointer_ to the status value location |
| 454 |
{return &exit_status;} |
| 455 |
static void DoThreadExit(ExitStatus exitStatus) {pthread_exit(exitStatus);} |
| 456 |
#endif // if/else WIN32/UNIX |
| 457 |
|
| 458 |
bool IsMyself() {return (GetCurrentThread() == thread_id);} |
| 459 |
void DestroyThread(); |
| 460 |
|
| 461 |
bool InstallBreak(); |
| 462 |
bool SetBreak(); |
| 463 |
void RemoveBreak(); |
| 464 |
|
| 465 |
/** |
| 466 |
* @class Stream |
| 467 |
* |
| 468 |
* @brief This class helps manage notification for |
| 469 |
* protoSockets and generic I/O descriptors |
| 470 |
*/ |
| 471 |
class Stream : public ProtoNotify, public ProtoTree::Item, public ProtoQueue::Item |
| 472 |
{ |
| 473 |
public: |
| 474 |
enum Type {GENERIC, SOCKET, CHANNEL, TIMER, EVENT}; |
| 475 |
Type GetType() const {return type;} |
| 476 |
|
| 477 |
bool IsInput() const {return NotifyFlagIsSet(NOTIFY_INPUT);} |
| 478 |
bool IsOutput() const {return NotifyFlagIsSet(NOTIFY_OUTPUT);} |
| 479 |
|
| 480 |
virtual Descriptor GetInputHandle() const = 0; |
| 481 |
virtual Descriptor GetOutputHandle() const = 0; |
| 482 |
|
| 483 |
#ifdef WIN32 |
| 484 |
int GetIndex() const {return index;} |
| 485 |
void SetIndex(int theIndex) {index = theIndex;} |
| 486 |
int GetOutdex() const {return outdex;} |
| 487 |
void SetOutdex(int theOutdex) {outdex = theOutdex;} |
| 488 |
#endif // WIN32 |
| 489 |
protected: |
| 490 |
Stream(Type theType); |
| 491 |
|
| 492 |
private: |
| 493 |
// ProtoTree::Item required overrides |
| 494 |
virtual const char* GetKey() const = 0; |
| 495 |
virtual unsigned int GetKeysize() const = 0; |
| 496 |
|
| 497 |
Type type; |
| 498 |
#ifdef WIN32 |
| 499 |
int index; |
| 500 |
int outdex; |
| 501 |
#endif // WIN32 |
| 502 |
}; // end class Stream |
| 503 |
|
| 504 |
|
| 505 |
// Declare indexed table of streams |
| 506 |
// (will be indexed by ProtoChannel, ProtoSocket, etc pointer) |
| 507 |
class StreamTable : public ProtoTreeTemplate<Stream> {}; |
| 508 |
|
| 509 |
// Simple linked list of streams (we use for "ready_stream_list" |
| 510 |
class StreamList : public ProtoSimpleQueueTemplate<Stream> |
| 511 |
{ |
| 512 |
public: |
| 513 |
StreamList() : ProtoSimpleQueueTemplate<Stream>(true) {} // use container pooling |
| 514 |
~StreamList() {} |
| 515 |
}; // end class ProtoDispatcher::StreamList |
| 516 |
|
| 517 |
// The "UpdateStreamNotification()" method is implemented with system-specific code |
| 518 |
// (i.e. for the separate WIN32, USE_SELECT, USE_KQUEUE, and USE_EPOLL cases) |
| 519 |
enum NotificationCommand {DISABLE_ALL, ENABLE_INPUT, DISABLE_INPUT, ENABLE_OUTPUT, DISABLE_OUTPUT}; |
| 520 |
bool UpdateStreamNotification(Stream& stream, NotificationCommand cmd); |
| 521 |
|
| 522 |
|
| 523 |
/** |
| 524 |
* @class SocketStream |
| 525 |
* |
| 526 |
* @brief This class helps manage notification for |
| 527 |
* ProtoSockets and generic I/O descriptors |
| 528 |
*/ |
| 529 |
class SocketStream : public Stream |
| 530 |
{ |
| 531 |
public: |
| 532 |
SocketStream(ProtoSocket& theSocket); |
| 533 |
ProtoSocket& GetSocket() {return *socket;} |
| 534 |
void SetSocket(ProtoSocket& theSocket) {socket = &theSocket;} |
| 535 |
#ifdef WIN32 |
| 536 |
Descriptor GetInputHandle() const |
| 537 |
{return socket->GetInputEventHandle();} |
| 538 |
Descriptor GetOutputHandle() const |
| 539 |
{return socket->GetOutputEventHandle();} |
| 540 |
#else |
| 541 |
Descriptor GetInputHandle() const |
| 542 |
{return socket->GetHandle();} |
| 543 |
Descriptor GetOutputHandle() const |
| 544 |
{return socket->GetHandle();} |
| 545 |
#endif // if/else WIN32/UNIX |
| 546 |
|
| 547 |
private: |
| 548 |
const char* GetKey() const |
| 549 |
{return (const char*)(&socket);} |
| 550 |
unsigned int GetKeysize() const |
| 551 |
{return (sizeof(ProtoSocket*) << 3);} |
| 552 |
|
| 553 |
ProtoSocket* socket; |
| 554 |
}; // end class SocketStream |
| 555 |
SocketStream* GetSocketStream(ProtoSocket& theSocket); |
| 556 |
void ReleaseSocketStream(SocketStream& socketStream); |
| 557 |
|
| 558 |
class SocketStreamPool : public ProtoTreeTemplate<SocketStream>::ItemPool {}; |
| 559 |
|
| 560 |
/** |
| 561 |
* @class ChannelStream |
| 562 |
* |
| 563 |
* @brief This class helps manage notification for |
| 564 |
* protoSockets and generic I/O descriptors |
| 565 |
*/ |
| 566 |
class ChannelStream : public Stream |
| 567 |
{ |
| 568 |
public: |
| 569 |
ChannelStream(ProtoChannel& theChannel); |
| 570 |
ProtoChannel& GetChannel() {return *channel;} |
| 571 |
void SetChannel(ProtoChannel& theChannel) {channel = &theChannel;} |
| 572 |
|
| 573 |
Descriptor GetInputHandle() const |
| 574 |
{return channel->GetInputEventHandle();} |
| 575 |
Descriptor GetOutputHandle() const |
| 576 |
{return channel->GetOutputEventHandle();} |
| 577 |
private: |
| 578 |
const char* GetKey() const |
| 579 |
{return (const char*)(&channel);} |
| 580 |
unsigned int GetKeysize() const |
| 581 |
{return (sizeof(ProtoChannel*) << 3);} |
| 582 |
|
| 583 |
ProtoChannel* channel; |
| 584 |
}; // end class ChannelStream |
| 585 |
ChannelStream* GetChannelStream(ProtoChannel& theChannel); |
| 586 |
void ReleaseChannelStream(ChannelStream& channelStream); |
| 587 |
|
| 588 |
class ChannelStreamPool : public ProtoTreeTemplate<ChannelStream>::ItemPool {}; |
| 589 |
|
| 590 |
|
| 591 |
/** |
| 592 |
* @class TimerStream |
| 593 |
* |
| 594 |
* @brief This class lets us have a "Stream*" pointer |
| 595 |
* for the user data in "struct epoll_event" since we |
| 596 |
* use the "event.data" for that purpose. |
| 597 |
*/ |
| 598 |
class TimerStream : public Stream |
| 599 |
{ |
| 600 |
public: |
| 601 |
TimerStream(); |
| 602 |
~TimerStream(); |
| 603 |
|
| 604 |
void SetDescriptor(Descriptor theDescriptor) |
| 605 |
{descriptor = theDescriptor;} |
| 606 |
Descriptor GetDescriptor() const |
| 607 |
{return descriptor;} |
| 608 |
Descriptor GetInputHandle() const |
| 609 |
{return descriptor;} |
| 610 |
Descriptor GetOutputHandle() const |
| 611 |
{return descriptor;} |
| 612 |
private: |
| 613 |
const char* GetKey() const {return NULL;} |
| 614 |
unsigned int GetKeysize() const {return 0;} |
| 615 |
|
| 616 |
private: |
| 617 |
Descriptor descriptor; |
| 618 |
}; // end class TimerStream |
| 619 |
|
| 620 |
/** |
| 621 |
* @class EventStream |
| 622 |
* |
| 623 |
* @brief This class helps manage notifications |
| 624 |
* for ProtoEvent instances |
| 625 |
*/ |
| 626 |
class EventStream : public Stream |
| 627 |
{ |
| 628 |
public: |
| 629 |
EventStream(ProtoEvent& theEvent); |
| 630 |
~EventStream(); |
| 631 |
|
| 632 |
void SetEvent(ProtoEvent& theEvent) {event = &theEvent;} |
| 633 |
ProtoEvent& GetEvent() {return *event;} |
| 634 |
|
| 635 |
Descriptor GetDescriptor() const |
| 636 |
{return (NULL != event) ? event->GetDescriptor() : INVALID_DESCRIPTOR;} |
| 637 |
Descriptor GetInputHandle() const {return GetDescriptor();} |
| 638 |
Descriptor GetOutputHandle() const {return GetDescriptor();} |
| 639 |
|
| 640 |
private: |
| 641 |
const char* GetKey() const |
| 642 |
{return (const char*)(&event);} |
| 643 |
unsigned int GetKeysize() const |
| 644 |
{return (sizeof(ProtoEvent*) << 3);} |
| 645 |
|
| 646 |
private: |
| 647 |
ProtoEvent* event; |
| 648 |
}; // end class EventStream |
| 649 |
EventStream* GetEventStream(ProtoEvent& theEvent); |
| 650 |
void ReleaseEventStream(EventStream& eventStream); |
| 651 |
class EventStreamPool : public ProtoTreeTemplate<EventStream>::ItemPool {}; |
| 652 |
|
| 653 |
/** |
| 654 |
* @class GenericStream |
| 655 |
* |
| 656 |
* @brief This class helps manage notification for |
| 657 |
* protoSockets and generic I/O descriptors |
| 658 |
*/ |
| 659 |
class GenericStream : public Stream |
| 660 |
{ |
| 661 |
public: |
| 662 |
GenericStream(Descriptor theDescriptor); |
| 663 |
Descriptor GetDescriptor() {return descriptor;} |
| 664 |
void SetDescriptor(Descriptor theDescriptor) {descriptor = theDescriptor;} |
| 665 |
void SetCallback(Callback* theCallback, const void* clientData = NULL) |
| 666 |
{ |
| 667 |
callback = theCallback; |
| 668 |
client_data = clientData; |
| 669 |
} |
| 670 |
void OnEvent(Event theEvent) |
| 671 |
{if (callback) callback(descriptor, theEvent, client_data);} |
| 672 |
|
| 673 |
const char* GetDescriptorPtr() const |
| 674 |
{return ((const char*)&descriptor);} |
| 675 |
|
| 676 |
Descriptor GetInputHandle() const |
| 677 |
{return descriptor;} |
| 678 |
Descriptor GetOutputHandle() const |
| 679 |
{return descriptor;} |
| 680 |
|
| 681 |
//private: |
| 682 |
const char* GetKey() const |
| 683 |
{return (const char*)(&myself);} |
| 684 |
unsigned int GetKeysize() const |
| 685 |
{return (sizeof(GenericStream*) << 3);} |
| 686 |
|
| 687 |
GenericStream* myself; // used as StreamTable key |
| 688 |
Descriptor descriptor; |
| 689 |
Callback* callback; |
| 690 |
const void* client_data; |
| 691 |
}; // end class GenericStream |
| 692 |
|
| 693 |
// This class is used to keep a separate listing of GenericStreams indexed |
| 694 |
// by their descriptors so we can find them quickly. |
| 695 |
class GenericStreamTable : public ProtoIndexedQueueTemplate<GenericStream> |
| 696 |
{ |
| 697 |
public: |
| 698 |
GenericStream* FindByDescriptor(Descriptor descriptor) const |
| 699 |
{return Find((const char*)&descriptor, sizeof(Descriptor) << 3);} |
| 700 |
|
| 701 |
private: |
| 702 |
// Required overrides for ProtoIndexedQueue subclasses |
| 703 |
virtual const char* GetKey(const Item& item) const |
| 704 |
{return static_cast<const GenericStream&>(item).GetDescriptorPtr();} |
| 705 |
virtual unsigned int GetKeysize(const Item& /*item*/) const |
| 706 |
{return (sizeof(Descriptor) << 3);} |
| 707 |
}; // end ProtoDispatcher::GenericStreamTable |
| 708 |
|
| 709 |
class GenericStreamPool : public ProtoTreeTemplate<GenericStream>::ItemPool {}; |
| 710 |
|
| 711 |
GenericStream* GetGenericStream(Descriptor descriptor); |
| 712 |
GenericStream* FindGenericStream(Descriptor descriptor) const |
| 713 |
{return generic_stream_table.FindByDescriptor(descriptor);} |
| 714 |
void ReleaseGenericStream(GenericStream& genericStream); |
| 715 |
|
| 716 |
// Members |
| 717 |
StreamTable stream_table; // table of active streams by channel, socket, etc pointer |
| 718 |
GenericStreamTable generic_stream_table; // Used to lookup stream by "descriptor" value |
| 719 |
|
| 720 |
ChannelStreamPool channel_stream_pool; // land of inactive channel streams |
| 721 |
SocketStreamPool socket_stream_pool; // land of inactive socket streams |
| 722 |
EventStreamPool event_stream_pool; // land of inactive event streams |
| 723 |
GenericStreamPool generic_stream_pool; // land of inactive generic streams |
| 724 |
|
| 725 |
volatile bool run; |
| 726 |
WaitStatus wait_status; |
| 727 |
int exit_code; |
| 728 |
double timer_delay; // ( timer_delay < 0.0) means INFINITY |
| 729 |
bool precise_timing; |
| 730 |
ThreadId thread_id; |
| 731 |
bool external_thread; |
| 732 |
bool priority_boost; |
| 733 |
volatile bool thread_started; |
| 734 |
volatile bool thread_signaled; |
| 735 |
Mutex suspend_mutex; |
| 736 |
Mutex signal_mutex; |
| 737 |
ThreadId thread_master; |
| 738 |
unsigned int suspend_count; |
| 739 |
unsigned int signal_count; |
| 740 |
Controller* controller; |
| 741 |
|
| 742 |
// The "prompt" stuff here was a hack to be able to make a threaded |
| 743 |
// ProtoDispatcher do some "work" (prompt_callback) in its thread |
| 744 |
bool prompt_set; |
| 745 |
PromptCallback* prompt_callback; |
| 746 |
const void* prompt_client_data; |
| 747 |
ProtoEvent break_event; |
| 748 |
EventStream break_stream; |
| 749 |
bool is_signaled; |
| 750 |
#ifdef WIN32 |
| 751 |
int Win32AddStream(Stream& theStream, HANDLE theHandle); |
| 752 |
void Win32RemoveStream(int index); |
| 753 |
bool Win32IncreaseStreamArraySize(); |
| 754 |
static LRESULT CALLBACK MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); |
| 755 |
#ifdef _WIN32_WCE |
| 756 |
static DWORD WINAPI DoThreadStart(LPVOID lpParameter); |
| 757 |
#else |
| 758 |
static unsigned int __stdcall DoThreadStart(void* lpParameter); |
| 759 |
#endif // if/else _WIN32_WCE |
| 760 |
ExitStatus exit_status; |
| 761 |
enum {DEFAULT_STREAM_ARRAY_SIZE = 32}; |
| 762 |
HANDLE* stream_handles_array; |
| 763 |
Stream** stream_ptrs_array; |
| 764 |
DWORD stream_array_size; |
| 765 |
DWORD stream_count; |
| 766 |
HWND msg_window; |
| 767 |
HANDLE actual_thread_handle; |
| 768 |
StreamList ready_stream_list; // list of input or output "ready" streams |
| 769 |
#ifdef USE_WAITABLE_TIMER |
| 770 |
TimerStream timer_stream; |
| 771 |
bool timer_active; |
| 772 |
#endif // USE_WAITABLE_TIMER |
| 773 |
#else // UNIX |
| 774 |
|
| 775 |
#ifdef USE_TIMERFD |
| 776 |
int timer_fd; |
| 777 |
#endif // USE_TIMERFD |
| 778 |
static void* DoThreadStart(void* arg); |
| 779 |
int exit_status; |
| 780 |
|
| 781 |
#if defined(USE_SELECT) |
| 782 |
fd_set input_set; |
| 783 |
fd_set output_set; |
| 784 |
#elif defined(USE_KQUEUE) |
| 785 |
enum {KEVENT_ARRAY_SIZE = 64}; |
| 786 |
bool KeventChange(uintptr_t ident, int16_t filter, uint16_t flags, void* udata); |
| 787 |
struct kevent kevent_array[KEVENT_ARRAY_SIZE]; |
| 788 |
int kevent_queue; |
| 789 |
#elif defined(USE_EPOLL) |
| 790 |
enum {EPOLL_ARRAY_SIZE = 64}; |
| 791 |
bool EpollChange(int fd, int events, int op, void* udata); |
| 792 |
struct epoll_event epoll_event_array[EPOLL_ARRAY_SIZE]; |
| 793 |
int epoll_fd; |
| 794 |
#else // UNIX |
| 795 |
#error "undefined async i/o mechanism" // to make sure we implement something |
| 796 |
#endif // !USE_SELECT && !USE_KQUEUE |
| 797 |
#ifdef USE_TIMERFD |
| 798 |
TimerStream timer_stream; |
| 799 |
#endif // USE_TIMERFD |
| 800 |
#endif // if/else WIN32/UNIX |
| 801 |
|
| 802 |
const void* user_data; |
| 803 |
|
| 804 |
}; // end class ProtoDispatcher |
| 805 |
|
| 806 |
#endif // _PROTO_DISPATCHER |