OS/161 Threads

The objective of this lab is to gain understanding on how to use OS161's thread library. There is also a little challenge at the end for those of you who would like to gain a broader understanding on the topic.

exercise 1, multi-threaded hello world

The objective of this exercise is to become familiar with OS161's thread related system calls located in src/kern/include/thread.h and src/kern/thread/ .

First, make sure you happy with assignment0. Once you have done assignment0 and have submitted it, then read on.

Modifying your Kernel

We will now go through the steps required to modify and rebuild your kernel. We will add a new file to the sources. The file contains a function we will call from existing code. We need to add the file to the kernel configuration, re-config the kernel, and then rebuild again.

exercise 2, Simple synchronisation

Now that we have successfully created a thread it is time to see how some the other thread related function work.Take another looks at kern/include/thread.h

exercise 3, pthread synchronisation

As you have seen in lectures OS/161 is not the only OS to have threads, Linux and most other UNIXs also have support for threads. One of the most commonly used thread libraries on Linux is called "POSIX Threads" or pthread. Some guide on pthreads can be found at

In this exercise, we will use pthread's synchronisation mechanisms to solve some simple problems, not OS161.

Mutex

For the mutex program you need to make thread obey their order so that thread 1 counts then thread 2 then thread 3 and so on. You may not remove the sleep() call or alter the section that makes them sleep for a random number of seconds.

In the end the out put should look like

% ./mutex
Mutex program starting. 
Hello world, I'm thread 1
Hello world, I'm thread 2
Hello world, I'm thread 3
Hello world, I'm thread 4
Hello world, I'm thread 5
Hello world, I'm thread 6
Hello world, I'm thread 7
Hello world, I'm thread 8
Hello world, I'm thread 9
Hello world, I'm thread 10
thread  1  counting   1
thread  2  counting   2
thread  3  counting   3
thread  4  counting   4
thread  5  counting   5
thread  6  counting   6
thread  7  counting   7
thread  8  counting   8
thread  9  counting   9
thread  10  counting  10
thread  1  counting  11
thread  2  counting  12
thread  3  counting  13
...

Dead lock

The deadlock program has the classical deadlock example of two thread that need two resources A and B. The two threads attempt to acquire the renounces in opposite orders, you need to resolve the deadlock.

The labs are not assessable so don't solve them the easy way, use pthread synchronisation primitives to solve the problem.

Happy hacking :)