View
216
Download
2
Embed Size (px)
Citation preview
1
Lecture 11Lecture 11
Operating System Interaction
This lecture covers three items, thread, is the most interesting as it makes the system faster if you know how to use it properly.
Dynamic Linking
Time-Sharing
Threads
2Dynamic Linking
It means to link the library during run time, not compilation time.
Libraries
Dynamic-Link Libraries (DLLs)
Example of DLL
3Library in Visual C++
4Example of linking
5Explanation – static (it means fixed)
In the above diagram, the application object has to link with malloc() and calling main() to form an executable (exe) file.
6 Dynamic-Link Libraries (DLLs) – not fixed during compilation
Dynamic linking means where linking is performed on demand at runtime.
An advantage of dynamic linking is that executable files can be much smaller than statically linked executables.
Of course, the executable is not complete without all of the associated library files, but if many executables share a set of libraries, there can be a significant, overall savings.
When you want
to run
7Fixed and Dynamic Linking
User’s Code
Library
User’s Code
Library
Library
8Advantage of DLL (1)
In most systems, the space savings extend to memory.
When libraries are dynamically linked, the operating system can arrange to let applications share the library code so that only one copy of the library is loaded into memory.
With static linking, each executable is a monolithic binary program. If several programs are using the same libraries, there will be several copies of the code in memory.
9Advantage of DLL(2)
Another potential memory savings comes from the fact that dynamically linked libraries do not necessarily need to be loaded. For example, an image editor may support input and output of dozens of file formats. It could be expensive (and unnecessary) to link conversion routines for all of these formats.
With dynamic linking, the program can link code as it becomes useful, saving time and memory. This can be especially useful in programs with ever growing lists of features.
10Disadvantage of DLL
First, there are version problems. Like all software, libraries tend to develop.
New libraries may be incompatible with old libraries in subtle ways.
If you update the libraries used by a program, it may have good, bad, or no effects on the program's behavior.
In contrast, a statically linked program will never change its behavior unless the entire program is relinked and installed.
11Example of DLL
DLL Initialization C Names and C++ Decorated Names The .DEF File Calling Conventions Building and Linking Testing the DLL DLL Precautions Using Declarations instead of .DEF Files Backward Compatibility Explicit Control over Run-Time Linking Summary
No need to memorise
12 Simple DLL program
For the following program, the library will export an integer function that adds one to its integer parameter
int mydll_data = 0;int mydll_function(int n) { mydll_data = n; return n + 1; }
13DLL Initialization
the function in mydll.cpp declared as:
BOOL __stdcall DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
This routine is called when the DLL is loaded and unloaded.
14C Names and C++ Decorated Names
Consider the following, where myfunc is defined three times: (how can we differentiate?)
class c1 { public: int myfunc(); int myfunc(int n); }; class c2 { public: int myfunc(); };
15Differentiation
int mydll_function(void)
might appear in the object file as the symbol:
?mydll_function@@YAHXZ
Yes, the symbol name actually starts with "?"! The extra characters encode enough type and scope information to make this symbol unique to this declaration of
mydll_function. That is three functions can be identified.
16The .DEF File
Before we build the DLL, we need to specify the interface to the DLL. In other words, you need to specify what symbols will be visible to other programs that load the DLL. This is done by adding a .DEF file to the project (Click Project. Then click Add To Project. Then click Files. Then choose the .DEF file). The file for this project is mydll.def, shown here:
LIBRARY MYDLL DESCRIPTION "Demonstrates a simple DLL" EXPORTS mydll_function @1 mydll_data @2
No need to memorise
17
Building and Linking
Note the table
18
Calling procedure
19
DLL Precautions
1. You must specify what symbols are exported from a DLL—for example, using a .DEF file.
2. If you use a .DEF file, you must be careful about names. You can either use "decorated" C++ names (later we will see where to find them), or you can use extern "C" {...} to specify simple names.
3. The program must be linked with the .lib file that corresponds to the .dll file.
4. Functions are typically declared with __stdcall, making DLLs accessible by programs written in other languages.
5. The DLL must be available at run time. In this example, we copied mydll.dll to the same folder as dlltest.exe.
6. Data imported using a .DEF file must be declared using __declspec(dllimport).
No need to memorise
20
Using Declarations instead of .DEF Files
In many cases, you can avoid a lot of work by using special declarations in your DLL. These declarations can do the job of the .DEF file, which not only saves work but avoids the need for decorated names or extern "C" declarations.
21Summary
Dynamic linking is an important mechanism for structuring programs and operating systems, especially in Windows systems.
As programs become large and offer more and more features, it becomes important to view them as collections of subsystems that can be configured as needed. DLLs allow programs to share code on disk and in memory, making them smaller and more efficient.
DLLs can be updated to add features or to fix bugs
22Time-Sharing
Why Time-Share a PC? – to support more processes and make use of the power of CPU
Context Switching - switching amongst processes, here, there is a need to prepare from process 1 to process 2
Process 1 Process 2 Process 3
23Why Time-Share a PC?
Time-sharing occurs when more than one program executes at the same time.
Unless there is more than one processor, programs do not actually execute simultaneously, but a rapid switching of the processor from one program to the next gives the impression of simultaneous execution.
24Example of process – Windows XP
25System Calls
To simplify the programming. Say, for example, you can call malloc() to grab memory instead of writing a subroutine to handle memory allocation.
26Other reasons of having system call
It is to protect the memory
1. Each executing program has its own memory. It is not possible for one process to directly access the memory of another process.
2.No process is allowed to "steal" the processor. Even if a program tries to execute an infinite loop, a timer eventually interrupts the processor and transfers control to some other processes.
3.Processes are not allowed free access to input/output devices such as the screen, the disk, and the network.
27Context Switching
To switch among processes
Each process is allocated to use the CPU for a quantum. This quantum is about 20 ms.
Say you have three processes, CPU will execute P1 (about 20 ms), P2 (about 20 ms) and P3 (20 ms), P1 or P2 again depending whether P1 is ready. P1 might wait for a request from a disk.
28Example of Context Switching
CPU
CPU
CPU
CPU
CPU
CPU
CPU
CPU
CPU
CPU
CPU
CPU
29Process state
Here, there are three states for one process. Running means it uses the CPU, ready means it is ready to use the CPU,while suspended means it is waiting for an I/O.
30Non-Preemptive process
Must finish before CPU can switch to others, say you have three processes, P1, P2, P3
31Preemptive process
CPU can switch to the other processes without finishing the current process, say from p1 to p2
32Threads
This lecture covers thread which is a light weight process.
Threads vs. Processes
Applications of Threads
Reentrant Code
Concurrent Data Access
Scheduling Effects
33Threads vs. Processes
What is different? Thread and process
Processes are ideal for running independent programs but sometimes we want to use multiple processes in a single program.
A thread is essentially the same as a process except that threads share a single address space.
You can create a process or a thread using
CreateProcess()…. CreateThread()
34Advantages of Using Thread
First, there is considerable cost to creating a virtual address space and changing address spaces with each context switch. Threads can eliminate the need to change address spaces after a context switch. (thread is simpler than process)
Secondly, and perhaps more importantly, due to the fact that threads share memory, threads can share data much more easily. (thread can share memory easier than process)
35Applications of Threads
What are the applications?Background Processing (Some programs have operations that run for many seconds, minutes, or even hours, it is better to use threads for these operations.)
Asynchronous I/O (Normally, when a program reads or writes to a file, the I/O operation does not return until it is complete). Sometimes, a program can continue without waiting for completion.
36Application
37 Applications of ThreadsPrefetching (Asynchronous input is sometimes called prefetching because data is read (fetched) before it is needed.
File systems often prefetch data, so setting up a thread to prefetch data from a file is probably not a good idea.)For example, while reading an image, your browser could pre-load the next image.
38Push-Pull Conversion – use a file for communication or event to control the flow
39
Solution – to multi-threads
Create two threads, one to read, while the
other is to write and use events to control the
flow of data. Otherwise, the data in the buffer
will be corrupted.
40Applications
Real-Time Systems (A program may have a combination of high-priority, time-critical tasks and less important, non-time-critical tasks.
For example, an MP3 audio player must decode audio samples and deliver them to an audio output device at a rate of 44100 sample pairs (for stereo quality) per second)
41Example of reentrant code
if (i != 0) x = 1.0 / i;
It seems to be it is true for a single task, but might not be true in multi-thread/multi-task, as i can be changed by other thread during context switching.
Switching amongst processes
42Another example
int temp;
void swap(int a[], int i, int j) { temp = a[i]; a[i] = a[j]; a[j] = temp; }
43Need of synchronisation
There are many methods to prevent data corruption due to mis-synchronisation such as:
Critical_section (enter critical section and leave critcial section, use SetEvent and WaitForSingle Object to wait unitl one of the threads has finished modified the data.)
You can use the above in your lab. to play around it.
44
Scheduling Effects
45Summary
Dynamic linking
Time sharing
Process
Threads