VE482 — Introduction to Operating Systems Assignment 4 solved


Category: You will receive a download link of the .ZIP file upon Payment


5/5 - (1 vote)

Ex. 1 — Simple questions
1. Consider a system in which threads are implemented entirely in user space, with the run-time
system getting a clock interrupt once a second. Suppose that a clock interrupt occurs while some
thread is executing in the run-time system. What problem might occur? Can you suggest a way
to solve it?
2. Suppose that an operating system does not have anything like the select system call (man
select for more details on the command) to see in advance if it is safe to read from a file, pipe,
or device, but it does allow alarm clocks to be set that interrupt blocked system calls. Is it possible
to implement a threads package in user space under these conditions? Discuss.
Ex. 2 — Monitors
During the lecture monitors were introduced (3.36). They use condition variables as well as two instructions, wait and signal. A different approach would be to have only one operation called waituntil,
which would check the value of a boolean expression and only allow a process to run when it evaluates
as True. What would be the drawback of such a solution?
Ex. 3 — Race condition in Bash
Write a Bash script which generates a file composed of one integer per line. The script should read the
last number in the file, add one to it, and append the result to the file.
1. Run the script in both background and foreground at the same time. How long does it take before
observing a race condition?
2. Modify the script such as to prevent the race condition.
Ex. 4 — Programming with semaphores
The following C code creates two threads which increment a common global variable. When run it
generates a random and inaccurate output. In order to solve this problem we want to use semaphores.
1. On Linux, find the file semaphore.h.
2. Read the documentation to understand how to use the functions described in the file semaphore.h.
3. Using semaphores adjust the program such as to always return the correct answer.
1 #include ¡stdio.h¿
2 #include ¡stdlib.h¿
3 #include ¡pthread.h¿
4 #define N 1000000
5 int count = 0;
6 void * thread˙count(void *a) –
7 int i, tmp;
8 for(i = 0; i ¡ N; i++) –
9 tmp = count;
10 tmp = tmp+1;
11 count = tmp;
12 ˝
13 ˝
14 int main(int argc, char * argv[]) –
15 int i;
16 pthread˙t *t=malloc(2*sizeof(pthread˙t));
17 for(i=0;i¡2;i++) –
18 if(pthread˙create(t+i, NULL, thread˙count, NULL)) –
19 fprintf(stderr,”ERROR creating thread %d“n”, i);
20 exit(1);
21 ˝
22 ˝
23 for(i=0;i¡2;i++) –
24 if(pthread˙join(*(t+i), NULL)) –
25 fprintf(stderr,”ERROR joining thread“n”);
26 exit(1);
27 ˝
28 ˝
29 if (count ¡ 2 * N) printf(”Count is %d, but should be %d“n”, count, 2*N);
30 else printf(”Count is [%d]“n”, count);
31 pthread˙exit(NULL);
32 free(t);
33 ˝