Week 11 - July 22-26
Introduction
This week we study threads and mutexes. Threads allow us to perform parallel programming within a process.
Mutexes provide us with a synchronization mechanism to protect shared resources used by multiple threads.
We will also look at server design.
Videos
Quiz
Lecture Material
Labs
- Lab 8 - client/server with messaging.
- Lab 9 - Server with Multiple Clients and a Receive Thread with Mutexing.
Assignment
Introduction to Assignment 2.
Sample Code
Threads and Mutexes
- A simple introduction to threads can be found in counter.cpp. This program simply starts off 5 threads with a 1 second delay between each. Each thread counts 10 seconds.
Note that in the Makefile a link to the pthread library is made (LIBS=-lpthread). This is required wherever threads are used in the code.
- For a good discussion of processes vs threads, see the article
What’s the Diff: Programs, Processes, and Threads.
- This week we study threads and mutexes. Mutexing is to ensure our threads are synchronized and operations are atomic.
Atomic operations are the foundation on which other synchronization methods are built,
they provide instructions that execute atomically, without interruption. Atomic operators are indivisible instructions.
- Code that demonstrates the need for mutexes can be found in
counterNoMutex.cpp,
counterMutex.cpp, and
Makefile.
- In synchronizing threads with mutexes, one has to avoid thread deadlock.
Deadlock is a situation where a set of
processes are blocked because each process is holding a resource and waiting for another resource acquired by some other process.
- Code that demonstrates deadlock can be found in
deadlock.cpp and
Makefile.
- Code that demonstrates stream sockets with a separate receive thread for socket reads can be found in
client1.cpp,
server.cpp, and
Makefile.
Note that common resources are mutexed.
- Code that demonstrates INET sockets with a separate receive thread for socket reads can be found in
msgClient.cpp,
msgServer.cpp, and
Makefile.
Note that common resources are mutexed.
- A server can act as a message pump or dispatcher if it accepts messages from a number of clients and redirects these messages to a number of clients.
A client creates a message with the source client information and destination client information embedded in the messsage. The client sends this message
to a server which redirects it to the destination client.
Code that demonstrates this message pump or dispatcher using INET sockets with a separate receive thread for socket reads can be found in
msgClient.cpp,
msgPump.cpp,
startClient.sh,
stopClient.sh, and
Makefile.
Note that common resources are mutexed.
For the rationale behind such a central server, see the first six slides of
Sockets and the Implementation of a World Wide Messaging System.