Intermediate level tasks

Assignment Help Operating System
Reference no: EM1336557

Intermediate Level Tasks : Below is a simple program. It creates 2 threads. The first thread keeps printing out X on the screen, and the second thread keeps printing out O on the screen. Except for the thread activity part, you do not have to pay much attention to the program language details. When executing the program, due to the time sharing nature between the 2 threads, we expect to see this pattern of execution: "XXXOOOXXXOOO...". Although not really accurate, we can regard the number of Xs or Os in the output as the indicator of the duration of the execution of the corresponding thread in its allocated time slice. In an ideal round-robin time sharing situation, we would see the same number of Xs, followed by the same number of Os, and then Xs, and then Os, and forever (until the program is terminated by an external force).

NOTE: Exactly what happened during the course of the execution is actually unknown. The best we can do is to take an informed guess, which is close enough. As already stated, it is not really accurate to regard the number of Xs or Os in the output as the indicator of the duration of the execution of the corresponding thread in its allocated time slice. Printing out Xs or Os is actually I/O operation. In this question, we do not take this nature into account. The fundamental point for this question is that the execution in a time sharing environment is very unpredictable. Many unknown and also unpredictable factors can change the time allocation to the threads and processes. However, each individual thread or process, effectively, executes as in isolation, thanks to the context preserving and restoring operation.

#include <stdio.h>

#include <unistd.h>

#include <pthread.h>

 

// repeat the times (*) operation 100,000 times to slow down the

// execution of the instructions

#define RPT 100000

 

void* print_X() {     inti;     float x;

 while (1) {

      // consuming some CPU time to slow done the execution

 // no logic meaning; can be safely ignored        for(i=0; i<RPT; i++) { x = 3.1415926*3.1415926; }

 

printf("X"); 

    }

}  

void* print_O() {     inti;     float x;

 

    while (1) {

      for(i=0; i<RPT; i++) { x = 3.1415926*3.1415926; }        printf("O"); 

    }

}  

int main () {

 

pthread_t tid1, tid2;

pthread_create (&tid1, NULL, &print_X, NULL);     pthread_create (&tid2, NULL, &print_O, NULL);

 

// Wait till threads complete. Not really related to this 

// question in this assignment. Can be ignored.

pthread_join(tid1, NULL);     pthread_join(tid2, NULL);

 

printf ("\n==========================\n");

}

One execution of the program produced the following output, next page. Newlines and line numbers were added manually after the output was captured to make it more readable. Please explain:

1. Suppose that Line 1 of the output indicates that the thread completed the full duration of its allocated time slice. Has the thread completed its execution yet? If yes, which thread produced the output in Line 3, and how? If not, why cannot the thread continue its exclusion anymore? Please explain what happened behind the scene, which we cannot see from the output, at the end of the line to the beginning of the next line.

2.  Line 2 is shorter than Line 1. What could be the reason(s)?

3. What could be the possible reasons which caused the output from Line 08 to Line 15?

4. Will the effective execution output of the 2 threads be different, in this very program, when the computer is very busy and also with many interrupts in comparison with when the computer is almost idle with no other activities any all ?Why and why not?

Advanced Level Tasks 

For the following tasks, you should write a proper report to explain the logic of your programs and also answer the questions from the tasks. Your report should read like a textbook on programming. You can use figures and pieces of program code in the report to help you to explain. The full programs and the program outputs should be included at the end of the report as an appendix. A submission with only the programs and without the report will not attract any mark; neither will a report without the programs.

Task 1: Below is a program which mimics the web page counter, counting how many visits to a web page. The counter increases by 1 for every visit. To mimic multiple concurrent visits, a new thread is created in response to a connection from a remote web browser. A real web server actually behaves like this. The variable cnt is the counter and is shared by all threads.

#include <stdio.h>

#include <unistd.h>

#include <pthread.h>

 

// repeat 100 times to mimic 100 random visits to the page

#define RPT 100

 

//web page visit counter intcnt=0;

 void* counter() {

       intcntLocalCopy;

      float r;

 

      cntLocalCopy = cnt;

 

      // mimicking the work of the sever in serving the page to

      // the browser

      r = rand() % 2000; usleep(r);

 

      cnt = cntLocalCopy + 1;

}   int main () {     inti;     float r;

pthread_ttid[RPT];

 

    // seed the random number sequence      srand(time(NULL));

 for (i=0; i<RPT; i++) {

 

    // mimicking the random access to the web page          r = rand() % 2000; usleep(r);

 

        // a thread to respond to a connect from a browser         pthread_create (&tid[i], NULL, &counter, NULL);     }

 

// Wait till threads complete.      for (i=0; i<RPT; i++) {

pthread_join(tid[i], NULL);

    } 

// print out the counter value and the number of mimicked visits

// the 2 values should be the same if the program is written

// properly     printf ("cnt=%d, repeat=%d\n", cnt, RPT);

}

 

The program was executed a number of times and the following are the output of each run.

 

            cnt=63, repeat=100           cnt=59, repeat=100   cnt=58, repeat=100cnt=63, repeat=100              cnt=59, repeat=100

         cnt=59, repeat=100

 

1.      Explain why the counter value is smaller than the number of visits? From the list, the value of cnt is around 60. It is possible for the value be 50 or 70? Why or why not?

 

2.      Please re-implement this program on the platform (Linux or Windows) of your choice with the programming language of your choice and then apply a proper fix. Report the outcome of your fixed program, and also explain your fix. This sample program has been tested on a Linux platform. General hint: please search the Internet on the synchronisation primitives (e.g., mutex, semaphore, or monitor) and their usages on your platform with your programming language, e.g., googling "synchronisation primitive C pthreadlinux".  [; hint: please note that the difficult level of the task is not proportional to the mark, if measured by the scales of basic and intermediate level tasks]

Task 2: [hint: please note that the difficult level of the task is not proportional to the mark, if measured by the scales of basic and intermediate level tasks.] 

Write a program on the platform (Linux or Windows) of your choice with the programming language of your choice. The program has two threads running concurrently. The 2 threads share a single buffer, which can be implemented as an array, with the capacity of storing maximum 8 characters. 

Thread 1 endlessly performs the following actions in sequence.

  • Read one alphabet character at a time from the keyboard. The character can be followed by an "Enter" if you don't know how to pick up a key stroke straightaway without waiting for the "Enter" key.
  • Add the character into the buffer.

Thread 2 endlessly performs the following actions in sequence.

  • Read one character from the buffer at a time.
  • Remove the character from the buffer.
  • Change the case (upper to lower or vice versa) of the character.
  • Write the character, together with the number of the remaining characters in the buffer, to the console, e.g., [c:5].
  • Sleep for a random period of time. The period of time should be decided by a random number, which is different in each round of this action sequence. The random number should be large enough so that the shared buffer will have some characters at some time.

You should properly synchronize the two threads to guard the data integrity in the buffer so that there will be no misbehaviors. When running the program, please input about 8 characters with a random delay after each input, and then wait for a long time, long enough for all characters being removed from the buffer by Thread 2.

1.      What kind of display does the program produce? Explain the interaction, which is responsible for the display, between the 2 threads. 

2.      Explain how your program deals with the situation when the buffer is empty while Thread 2 is trying to read and remove a character from the buffer. Explain how your program deals with the situation when the buffer is full while Thread 1 is trying to add a character into the buffer. 

Reference no: EM1336557

Questions Cloud

Compare the effect of racial bias and politics on science : Compare and contrast the effect of racial bias and politics on science. If one of the main benefits of GM crops is increased yield, why are the majority of GM seeds sold to industrialized instead of developing countries?
What are the differences between science and religion : A 2600-3000 word "thought" paper.  What are the differences between science and religion.  While a thought paper can (and in this case, does) include research, it doesn't pretend to be objective.
Biology quiz : Biology Quiz: Using information at the CDC Influenza website, What is the most prevalent strain of influenza that is circulating in the 2012-13 flu season (Select one)?
How to best align operational structures with strategy : Analyse and evaluate the proposals of the authors about how to best align operational structures with strategy. With which perspective of operations strategy does the authors' proposal best fit? Analyse the four perspectives outlined by the authors t..
Intermediate level tasks : Intermediate Level Tasks :  Below is a simple program. It creates 2 threads. The first thread keeps printing out X on the screen, and the second thread keeps printing out O on the screen.
Design and implement tower of hanoi puzzle program : Task: Design and implement Tower of Hanoi Puzzle program using C# and Windows Presentation Foundation (WPF) template in Visual Studio 2012 or newer.
Expand or contract the expression : MTH-163 Precalculus I: Expand or contract the expression using the properties of logarithms. Find the exact value without using a calculator. If this is not possible, state why not.
Discuss different types of leadership : Write an report of  harvard style 2500 words excluding  Referencing,  Discuss different types of leadership and how they influence the workplace attitudes and behaviors of followers.
Question about applicant testing process : Prepare a short essay discussing some of the legal and ethical considerations of major types of test: cognitive abilities, motor and physical abilities, personality and interests, and achievement test.

Reviews

Write a Review

Operating System Questions & Answers

  Disk scheduling algorithm

Simulation of Elevator and Shortest Seek Time First

  Discuss an application that benefits barrier synchronization

Discuss an application that would benefit from the use of barrier synchronization

  Stand alone child process

Forking the child process

  Write a multi-threaded program

Write a multi-threaded program to solve producer and consumer problem

  Formulate the linear programming model for this problem

Formulate the linear programming model for this problem Plot a graph indicating and labelling clearly all the constraints, the feasible region (R) and the optimal point (X)

  Deadlock avoidance

i. Deadlock avoidance ii. Deadlock prevention and  iii. Deadlock detection

  Virtual machines

Virtual machines supported by a host operating system

  Define the term context switch

Define the term context switch. Explain how context switching takes place. (use a diagram, with two processes)

  Give three technical merits of unix

Give three technical merits of UNIX b) Differentiate between "clustered systems" and "real-time systems". c) Describe the purpose of using "trust relationship"

  Implement the parser in two iterations

Implement the parser in a separate file. Implement the main parser function in a separate file main.c

  Define critical path and cpm

Define Critical Path and CPM. Define Networks & Network scheduling

  Threads

Explain a complication that concurrent processing adds to an operating system.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd