Semaphores
A semaphore specifies the maximum number of threads that can access a critical section simultaneously. A binary semaphore (max number of threads = 1) works the same as sleeplock. In this lab, we will implement read/write semaphore.
Complete and test your semaphore implementation. Submit your semaphore.c and a document showing your test outputs (with different number of processes) via Blackboard. The submission deadline is 8pm on Friday 17 September 2021. This lab will contribute 5% towards your overall course marks.
We will first create the implementation of semaphores in xv6. First, define an appropriate structure for semaphores. In the file semaphore.h provided with this lab, there is an empty structure called semaphore. Fill in the necessary ingredients that are needed to implement a semaphore.
Create a file semaphore.c that implements the following three functions:
// initsema - set the max threads
// and initialize whatever is needed
void initsema(struct semaphore *lk, int count)
Add these function prototypes to def.h.
Add the following system call to sysfile.c for testing your semaphore implementation.
#include âsemaphore.hâ
. . .
int
sys_sematest(void)
{
static struct semaphore lk;
int cmd, ret = 0;
if (argint(0, &cmd) < 0)
return -1;
switch (cmd) {
case 0: initsema(&lk, 5); ret = 5; break;
case 1: ret = downsema(&lk); break;
case 2: ret = upsema(&lk); break;
}
return ret;
}
Complete the process to include this system call in xv6.
Since xv6 does not have threads implemented, we will use processes to test the semaphore. A user program sematest.c has been provided for you that makes use of this system call to test your semaphore implementation. Edit the Makefile so that this program is compiled together with xv6.
Check that your implementation works correctly by testing with several different number of processes allowed in the semaphore.