An Interlocked Queue of Messages
From here, you can download three files ready for use on Rabbit.
queue.h, and queue.cpp
define an interlocked queue for sending messages between threads.
"Interlocked" means that there is a special locking mechanism in place
to prevent two threads from modifying the queue at the same time,
which could result in the queu being totally destroyed and even the
program being crashed. the special functions grab() and release()
(which are defined inside threads.h and threads.c) provide the
locking. If you use them yourself, make absolutely sure that every
grab is followed very soon by a release with the same parameter.
The parameter to grab() and release() is called a Semaphore. It is
the lock. For every data objject that needs to be interlocked, a
specific semaphore should be created. For this project, the
queues are probably the only such structures.
message.h defines the messages that
are put on the queue. In this file the messages are so simple that
everything goes in the .h file and there is no .cpp file. You will
almost certainly need to define slightly more sophisticated messages,
which will require editing message.h, and maybe even creating message.cpp.
The one constructor needs to be given
the string that is to be sent, AND a pointer to the "creature" that
is sending it. This creature pointer is used to provide a kind of
"return address" so that a response may be sent back to the right
place.
You will have to define a "creature" class of your own. A creature
will have to include a protected queue for its incoming message
and a public "tell" method that is used to send it a message.
this might be a beginning:
class Creature
{ public:
Creature(string n): name(n) { }
void tell(Message *m) { queue.add(m); }
protected:
Queue queue;
string name; };
once you have created a creature:
Creature c("Fred");
other creatures talk to it like this:
c.tell(new Message("Hello, you.", this));
non-creatures (such as you) could perhaps use NULL as the return
address:
c.tell(new Message("Hello, you.", NULL));
anyway, all that is up to you.
Remember when you are using the threads library (threads.c or .o or .h)
you will have to lik\nk with CC -pthread..., and when
you are using ncurses you will have to link with
CC -lncurses. If you are using both, you will need to link
with both: CC -pthread -lncurses.