CSCI 485 lab 3: threads/semaphores

Given the recent discussion of buffering messages in queues as a means of communicating between the parts of an application meant for generating messages and the parts meant for sending them, or between the parts of an application meant for receiving messages and the parts meant for processing them, as well as the need for a generic buffer type, and the need for safe/synchronized access across the various application parts, today's lab topic will be combining pthreads, semaphores, and a templated buffer class.

The (rather unsightly) code mass for the example is in the following files:

The templated class allows you to define a (circular) buffer for whatever kind of data you want to store. Your main application could declare SharedBuffer<string> if you wanted to save messages as C++ strings, SharedBuffer<char*> if you wanted to save them as character arrays, etc.

The main routine in the threadTest.C application creates 5 threads that produce data and 5 that consume data (set in the constants at the start of that file) as well as a single shared circular buffer (of floats in this case) that the producers stick data into and the consumers read data from.

The pthread library is used for thread creation and semaphores are used to restrict access to the global buffer: only one thread (whether a producer or consumer) can access the buffer at any given instant.

The shared buffer has one mutex lock on the actual array storing the data and another for locking out access to the index positions (front/back/size/current).

Note that there is also a mutex on communication access (reading from the keyboard/writing to the terminal) to ensure that the I/O from different producers/consumers doesn't get mixedup.

Because of the use of a templated class for the buffer, all the templated method implementations are included in the .h file.

The objective for this lab is to see if you can get a listener to receive messages in one thread, putting them into the buffer, while your main application (in another thread) can process messages once they're in the queue.

(Or, similarly, get two threads going in the client - one to read messages from the user and put them in the buffer, the other checking the buffer and sending messages when it finds something there to send.)

For a quick rehash on pthreads:

For a quick rehash on mutexes in pthread: