Docsity

Threads and Interprocess Communication - Project | CS 333, Study Guides, Projects, Research of Operating Systems

Toggle sidebar
bg1
CS-333 Operating Systems
Page 1
Programming Project 2:
Threads and Interprocess Communication
Due Date:
Monday, October 17, 2005, start of class
Duration:
Two Weeks
Overview and Goal
In this project you will learn about threads and gain familiarity writing programs involving concurrency
control. You will begin by studying the thread package, which implements multi-threading. You will
make modifications and additions to the existing code. Then you will use the threads package to solve
some traditional concurrency problems.
In addition, you will gain familiarity programming in the Spankish language.
Step 1: Download the Files
Start by creating a directory for the files you’ll need for this project. You might call it cs333/p2. Then
download all the files from
~walpole/public_html/class/cs333/fall2005/spank/p2
into your directory. You should get the following files:
makefile
DISK
System.h
System.c
Runtime.s
Switch.s
List.h
List.c
Thread.h
Thread.c
Synch-starter.h
Synch-starter.c
Main-starter.h
Main-starter.c
After getting the files, you should rename
Synch-starter.h to Synch.h
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Threads and Interprocess Communication - Project | CS 333 and more Study Guides, Projects, Research Operating Systems in PDF only on Docsity!

Programming Project 2:

Threads and Interprocess Communication

Due Date: Monday, October 17, 2005, start of class

Duration: Two Weeks

Overview and Goal

In this project you will learn about threads and gain familiarity writing programs involving concurrency control. You will begin by studying the thread package, which implements multi-threading. You will make modifications and additions to the existing code. Then you will use the threads package to solve some traditional concurrency problems.

In addition, you will gain familiarity programming in the Spankish language.

Step 1: Download the Files

Start by creating a directory for the files you’ll need for this project. You might call it cs333/p2. Then download all the files from

~walpole/public_html/class/cs333/fall2005/spank/p

into your directory. You should get the following files:

makefile DISK System.h System.c Runtime.s Switch.s List.h List.c Thread.h Thread.c Synch-starter.h Synch-starter.c Main-starter.h Main-starter.c

After getting the files, you should rename

Synch-starter.h to Synch.h

Synch-starter.c to Synch.c Main-starter.h to Main.h Main-starter.c to Main.c

In this project, you will modify and hand in the following files:

Synch.c Main.c

After getting the files, you should be able to compile all the code (as is) with the UNIX make command. (Hint: If you get an error, make sure your PATH is set appropriately, as in project 1). The program executable we are building will be called “os”. You can execute the program by typing:

% make % spank –g os

In the course of your experimentation, you may modify other files besides Synch.c and Main.c, but the code you are required to write and turn in doesn’t require any changes to the other files. For example, you may wish to uncomment some of the print statements, to see what happens. However, your final versions of Synch.c and Main.c must work with the other files, exactly as they are distributed.

Be sure you copy all files. Even though there are similarities with some of the files used for the previous project, there may be some subtle but important differences.

Step 2: Study the Existing Code

The code provided in this project provides the ability to create and run multiple threads, and to control concurrency through several synchronization methods.

Start by looking over the System package. Focus on the material toward the beginning of file System.c, namely the functions:

print printInt printHex printChar printBool nl MemoryEqual StrEqual StrCopy StrCmp Min Max printIntVar printHexVar

run (and waiting for time on the CPU) will be kept in a linked list called the “ready list”. Threads that become BLOCKED will sit on other linked lists. Also look over the List.c code file.

The key class in this project is named Thread, and it is located in the Thread package along with other stuff (see Thread.h, Thread.c). For each thread, there will be a single Thread object. Thread is a subclass of Listable, which means that each Thread object contains a next pointer and can be added to a linked list.

The Thread package is central and you should study this code thoroughly. This package contains one class (called Thread) and several functions related to thread scheduling and time-slicing:

InitializeScheduler () IdleFunction (arg: int) Run (nextThread: ptr to Thread) PrintReadyList () ThreadStart () ThreadFinish () FatalError (errorMessage: ptr to array of char) SetInterruptsTo (newStatus: int) returns int TimerInterruptHandler ()

FatalError is the simplest function. We will call FatalError whenever we wish to print an error message and abort the program. Typically, we’ll call FatalError after making some check and finding that things are not as expected. FatalError will print the name of the thread invoking it, print the message, and then shut down. It will throw us into the SPANK emulator command line mode. Normally, the next thing to do might be to type the “st” command (short for “stack”), to see which functions and methods were active.

(Of course the information printed out by the emulator will pertain to only the thread that invoked FatalError. The emulator does not know about threads, and it is pretty much impossible to extract information about other threads by examining bytes in memory.)

The next function to look at is SetInterruptsTo, which is used to change the “I” interrupt bit in the CPU. We can use it to disable interrupts with code like this:

... = SetInterruptsTo (DISABLED)

and we can use it to enable interrupts:

... = SetInterruptsTo (ENABLED)

This function returns the previous status. This is very useful because we often want to DISABLE interrupts (regardless of what they were before) and then later we want to return the interrupt status to whatever it was before. In our kernel, we’ll often see code like:

var oldIntStat: int ...

oldIntStat = SetInterruptsTo (DISABLED) ... oldIntStat = SetInterruptsTo (oldIntStat)

Next take a look at the Thread class. Here are the fields of Thread:

name: ptr to array of char status: int systemStack: array [SYSTEM_STACK_SIZE] of int regs: array [13] of int stackTop: ptr to void

Here are the operations (i.e., methods) you can do on a Thread:

Init (n: ptr to array of char) Fork (fun: ptr to function (int), arg: int) Yield () Sleep () CheckOverflow () Print ()

Each thread is in one of the following states: JUST_CREATED, READY, RUNNING, BLOCKED, and UNUSED, and this is given in the status field. (The UNUSED status is given to a Thread after it has terminated. We’ll need this in later projects.)

Each thread has a name. To create a thread, you’ll need a Thread variable. First, initialize it, providing a name.

Each thread needs its own stack and space for this stack is placed directly in the Thread object in the field called systemStack. Currently, this is an array of 1000 words, which should be enough. (It is conceivable our code could overflow this limit; there is a check to make sure we don’t overflow this limited area.)

All threads in this project will run in System mode. Therefore the stack is called the “system stack”. In later projects, we’ll see that this stack is used only for kernel routines. User programs will have their own stacks in their virtual address spaces, but we are getting ahead of ourselves.

The Thread object also has space to store the state of the CPU, namely the registers. Whenever a thread switch occurs, the registers will be saved in the Thread object. These fields (regs and stackTop) are used by the assembly code routine named Switch.

After initializing a new Thread, we can start it running with the Fork method. This doesn’t immediately begin the thread execution; instead it makes the thread READY to run and places it on the readyList. The readyList is a linked list of Threads. All Threads on the readyList have status READY. ReadyList is a global variable. There is another global variable currentThread, which points to the currently executing Thread object; i.e., the Thread whose status is RUNNING.

routine which will execute a “reti” instruction. This will restore the state to exactly what it was before and the interrupted routine (whatever it was) will get to continue.

Note that this code maintains a variable called currentInterruptStatus. This is because it is rather difficult to query the “I” bit of the CPU. It is easier to just change the variable whenever a change to the interrupt status changes. We see this occurring in the TimerInterruptHandler function. Clearly interrupts will be disabled immediately after the interrupt occurs. And the Yield function will preserve the interrupt status. So when we return from Yield, interrupts will once again be disabled. Before returning to the interrupted thread, we set the currentInterruptStatus to ENABLED. (They must have been enabled before the interrupt occurred—or else it could not have occurred—so after we execute the “reti” instruction, the status will revert to what it was before, namely ENABLED.)

Now you are ready to start playing with and modifying the code! Please experiment with the code we have just discussed, as necessary to understand it.

Step 3: Run the “SimpleThreadExample” Code

Execute and trace through the output of SimpleThreadExample in file Main.c.

In TimerInterruptHandler there is a statement

printChar (‘_’)

which is commented out. Try uncommenting it. Make sure you understand the output.

In TimerInterruptHandler, there is a call to Yield. Why is this there? Try commenting this statement? What happens. Make sure you understand how Yield works here.

Step 4: Run the “MoreThreadExamples” Code

Trace through the output. Try changing this code to see what happens.

Step 5: Implement the “Mutex” Class

In this part, you must implement the class Mutex. The class specification for Mutex is given to you in Synch.h:

class Mutex superclass Object methods Init () Lock () Unlock () IsHeldByCurrentThread () returns bool

endClass

You will need to provide code for each of these methods. In Synch.c you’ll see a behavior construct for Mutex. There are methods for Init, Lock, Unlock, and IsHeldByCurrentThread, but these have dummy bodies. You’ll need to add the code for these four methods.

You will also need to add a couple of fields to the class specification of Mutex to implement the desired functionality.

How can you implement the Mutex class? Take a close look at the Semaphore class; your implementation of Mutex will be quite similar.

First consider the IsHeldByCurrentThread method, which may be invoked by any thread. The code of this method will need to know which thread is holding a lock on the mutex; then it can compare that to the currentThread to see if they are the same. So, consider adding a pointer to the thread holding the mutex. Of course, you’ll need to set it to the current thread whenever the mutex is locked. You might use a null value in this field to indicate that no thread is holding a lock on the mutex.

When a lock is requested on the mutex, you’ll need to see if any thread already has a lock on this mutex. If so, you’ll need to put the current process to sleep. For putting a thread to sleep, take a look at the method Semaphore.wait. At any one time, there may be zero, one, or many threads waiting to acquire a lock on the mutex; you’ll need to keep a list of these threads so that when an Unlock is executed, you can wake up one of them. As in the case of Semaphores, you should use a FIFO queue, waking up the thread that has been waiting longest.

It might also be a good idea to add an error check in the Lock method to make sure that the thread asking to lock the mutex doesn’t already hold a lock on the mutex. (This would probably indicate a logic error in the code using the mutex. It would lead to a deadlock, with a thread frozen, waiting for itself to release the lock.)

When a mutex lock is released (in the Unlock method), you’ll need to see if there are any threads waiting to acquire a lock on the mutex. You can choose one and move it back onto the readyList. Now the waiting thread will begin running when it gets a turn. The code in Semaphore.Signal does something similar.

After getting Mutex to work, you should be able to execute the TestMutex function.

Step 6: Implement the Producer-Consumer Solution

The textbook contains a discussion of the Producer-Consumer problem and includes a solution. Implement this in Spankish using the classes Mutex and Semaphore. Deal with multiple producers and multiple consumers, all sharing a single bounded buffer.

The Main package contains some code that will serve as a framework. The buffer is called buffer and contains up to BUFFER_SIZE (e.g., 5) characters. There are 5 producer processes, each modeled by a

Basis for Grading

In this course, the code you submit will be graded on both correctness and style. Correctness means that the code must work right and not contain bugs. Style means that the code must be neat, well commented, well organized, and easy to read.

In style, your code should match the code we are distributing to you. The indentation should be the same and the degree of commenting should be the same.

Regarding The Due Date and Time

Please bring your project submission to class. It will be due at the beginning of class. I will collect project submissions before lecture and I will not accept project submissions after I begin class. I do not want students to miss lectures because they are trying to finish up a project. Plan ahead. The due time is “hard. I will make extensions to deadlines in the case of medical emergencies and business travel if you contact me ahead of time.

Working Together

I encourage students to discuss the material in this class. Feel free to discuss the programming projects amongst yourselves.

However, this is not a group project. You must create the code on your own.

It is okay to look at someone else’s code for the purposes of helping that person or for comparing your different approaches, but each student must do the coding alone. You must type in every line of code you submit. You must not copy another student’s code. Do not look at some one else’s code, then turn around and type that code in. You must create your code on your own.

It will be considered cheating to copy code.

Questions/Comments via Email

Questions/comments may be directed to the mailing list, the TA, or to me; the best approach is through email.

[email protected]  Email to the class mailing list

If you email questions to me or the TA, please include “cs333” in the subject line so we don’t accidentally identify your email as junk! (This is not necessary with the mailing list, since “MailMan” automatically adds [cs333].)