Last Updated: 2025-11-30 Sun 13:46

CMSC216 HW12: Threads and Worms

CODE DISTRIBUTION: hw12-code.zip

CHANGELOG: Empty

1 Rationale

Basic working knowledge of a threading library is an essential element in any system programmer's toolkit. This HW is focused on the basics of the pthreads (POSIX Threads) library due to its widespread availability. The provided code introduces basic thread usage via a simple visual demo where threads run at different rates. Basic mechanics such as passing threads initialization arguments and utilizing mutexes to avoid race conditions are demonstrated. Completing the lab will give basic knowledge of the pthreads library and use of mutexes to coordinate multiple threads.

Associated Reading / Preparation

Bryant and O'Hallaron: Ch 12.3-6 covers threaded programming. Ch 12.5 discusses coordinating threads with Semaphores which are nearly identical in their use there as the Mutexes that are used in the provided code.

While not the focus, the provided code also utilizes Software Signals to terminate cleanly, covered in B&O Ch 8.5.

Grading Policy

Credit for this HW is earned by taking the associated HW Quiz which is linked under Gradescope. The quiz will ask similar questions as those that are present in the QUESTIONS.txt file and those that complete all answers in QUESTIONS.txt should have no trouble with the quiz.

Homework and Quizzes are open resource/open collaboration. You must submit your own work but you may freely discuss HW topics with other members of the class.

See the full policies in the course syllabus.

2 Codepack

The codepack for the lab contains the following files:

File Description
QUESTIONS.txt Questions to answer
Makefile Makefile to build programs below
worms_pthread.c Code to analyze for problems
worms.py Optional file to examine

3 What to Understand

Ensure that you understand

  • The function calls to create threads and wait for the completion of another thread along with structs used for this purpose.
  • The function calls used to set up and clean up mutexes along with associated structs
  • Calls which lock and unlock mutexes

4 Questions

Analyze these files and answer the questions given in QUESTIONS.txt.

                           _________________

                            HW 12 QUESTIONS
                           _________________


Write your answers to the questions below directly in this text file to
prepare for the associated quiz. Credit for the HW is earned by
completing the associated online quiz on Gradescope.


PROBLEM 1: The Setup
====================

A
~

  Compile and run `worm_pthread.c' using the provided Makefile. Make
  sure to follow the program prompts.  Describe what you observe as the
  program runs on the terminal.

  Note: when compiling code that uses PThreads library functions, link
  against that library via `-lpthread'.


B
~

  Examine the code and describe the types data associated with each of
  the following elements in the program.
  - The "board" which has several pieces of data
  - The "worms" which have several pieces of data


C
~

  Describe the area of code in `main()' which creates threads and awaits
  them finishing.
  - Describe the function which is used to start a thread running and
    its arguments. Consult the manual for documentation on this function
    if needed.
  - Describe the function which is used to wait until a thread finishes.


PROBLEM 2: The Worms
====================

A
~

  Examine the `worm_func()' function carefully.  You may wish to
  consider the specific data passed to these worms which are in the
  array of `wormparam_t' structs near the top of the source code.

  Describe the basic algorithm that worms follow to do their work.


B
~

  Describe how worms avoid both claiming the same piece of
  territory. What system call mechanism is used to ensure that two worms
  cannot claim the same area of the board? Describe the function calls
  that are used to accomplish this and what functions in `main()' are
  used to set up this coordination mechanism.


C
~

  Describe the logic that appears to cause worms to be 'fast' and
  'slow': how is this artificial speed actually created in the
  `worm_func()' code.

  While the speed differences of worms is an intended creation of the
  program, speculate as to what use threads can be when dealing with
  entities of different speeds.


Optional: The Printer
=====================

  The printing thread runs `print_func()'. This does not introduce any
  new concurrency techniques. However it does use some special display
  tricks, printing extremely strange output like
  ,----
  |   printf("\33[s");              // save cursor position
  |   printf("\33[?25l");           // hide cursor to avoid flicker
  |   printf("\33[u");              // restore cursor position
  `----
  This type of output also appears in some other places in the program.
  The strange looking characters are special sequences for *terminal
  control*. The program interpreting output can be manipulated in
  various ways to change the cursor position, color of text, and so
  forth.  This is an extremely old set of conventions that harkens back
  to a day when these special sequences would physically manipulate
  aspects of the machine in which they appeared.  Modern "terminal
  emulators" such as Gnome Terminal or XTerm which show a command line
  honor these conventions making it possible for programs to display
  information in the same position as is done here or take over the
  entire screen of the terminal such as vi and gdb do.

  Discussion of terminal control is beyond the scope of our course but
  does receive some treatment in Stevens/Rago and elsewhere.  You can
  read more about the history and insanity of terminal control and the
  escape sequences that give some control over them in
  <https://en.wikipedia.org/wiki/ANSI_escape_code>

  To program a more fully-featured terminal program, use a robust
  terminal control library such as ncurses.
  <https://en.wikipedia.org/wiki/Ncurses> This library is used in the
  below Python version of the worms program.


Optional Enrichment: Threads in Python
======================================

  Threads are not unique to C and the Pthreads library. Most modern
  programming environments include some version of them. The prototype
  version of the worms program was written in Python and can be found in
  `worms.py' and can be run via
  ,----
  | > ./worms.py
  `----

  - No territory or step numbers are tracked in the Python version; it
    runs until Ctrl-c is pressed
  - The `curses' library is used to manipulate the terminal screen which
    allows for boxes and color to be used but complicates the
    implementation somewhat.
  - Python features several types of mutual exclusion locks including
    one used here that can be re-locked by the same thread without
    negative effects.

  Time permitting, explore the code of `worms.py' and draw some
  parallels as to the C code.

Author: Chris Kauffman (profk@umd.edu)
Date: 2025-11-30 Sun 13:46