Operating System Fundamentals



Download 2.34 Mb.
View original pdf
Page30/66
Date06.03.2023
Size2.34 Mb.
#60834
1   ...   26   27   28   29   30   31   32   33   ...   66
OperatingSystemFundamentals
best answers from c, Lesson 2 C# Windows Forms
Critical Sections
A critical section is apart of code (or more often a set of variables) that must be accessed in a controlled way when dealing with a multi-threaded system. Again, as previously mentioned, it does not really matter if the multiple threads are within the same processor spread across multiple processes. Critical code sections are actually quite difficult to visualize, so we will start with a very simple example and buildup a solution technique. We will then introduce some more typical programming requirements. Suppose again that we have two threads which we will call threadA and threadB. This time both threads are responsible for doing some long calculation (the actual calculation is not relevant, and once the calculation is finished then each thread prints some information on the screen. We will add some additional complexity to cover anew topic. threadA()
{ Long calculation
System.out.print(“Thread A is finished “); For (II < 10; i++) {
System.out.print(i);
System.out.print(“ “);
}
System.out.println();
}
Let us assume that threadB looks identical except for the message ―Thread B is finished: ―.
Although these examples are nonsense, they are easy to describe and introduce the concept of a critical section of code.
First we consider what happens when we run threadA without adding threadB to the mix. This thread will perform some long calculation and then print out the numbers 0 through 9 on a

Operating System Fundamentals
42 single line with a space between each. The behavior of the program is really quite simple. However, if we now launch both threads at the same time we might end up with the scheduler switching back and forth several times. The result could look something like this Thread A is finished 0Thread Bis finished 0 1 2 1 2 3 4 5 6 7 3 4 5 6 7 8 8 9 9 We have marked the output from threadB using italics so that you can see what is happening. The problem is that the scheduler keeps switching back and forth between the two threads while they are printing to the screen. This is quite common. Most operating systems will take an IO request as a chance to reschedule the threads or processes. Unfortunately, there are no actual guarantees of when the rescheduling will occur. Our goal for this small program is to make sure that the output does not get mixed up. The problem is that all of the output statements in our threads are part of a critical section, which means that we do not want the other thread interfering while we are trying to write to the screen.

Download 2.34 Mb.

Share with your friends:
1   ...   26   27   28   29   30   31   32   33   ...   66




The database is protected by copyright ©ininet.org 2024
send message

    Main page