Practical 08: Multithreading

Operating Systems: Multithreading | Page 1 Practical 08: Multithreading Name: __________________________________ Roll no: ________________ Date: ____...
Author: Oswin Webb
2 downloads 0 Views 294KB Size
Operating Systems: Multithreading | Page 1

Practical 08: Multithreading Name: __________________________________ Roll no: ________________ Date: _________________________ Section: ______________________

Practical Objectives 1. Thread 2. Threads vs. Processes 3. Multiprocessing 4. Multithreading 5. Context Switch 6. POSIX Threads 7. Example 1: Independent threads 8. Example 2: Reader and Writer threads 9. Example 3: Reader and Writer threads with a delay in writer thread. 10. Example 4: Threads with searial read / write, (condition variables and mutex locking)

Attach this cover sheet to the front of the packet of materials you submit following the laboratory tasks .

Activities

Remarks

Signature

In-lab Exercises

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 2

Theory Thread Thread is the smallest unit of processing. It is scheduled by an OS. In general, it is contained in a process. So, multiple threads can exist within the same process. It shares the resources with the process: The memory, code (instructions), and global variable (context - the values that its variables reference at any given moment). On a single processor, each thread has its turn by multiplexing based on time. On a multiple processor, each thread is running at the same time with each processor/core running a particular thread. Threads vs. Processes Processes and threads are related to each other but are fundamentally different. A process can be thought of as an instance of a running program. Each process is an independent entity to which system resources such as CPU time, memory, etc. are allocated and each process is executed in a separate address space. If we want to access another process' resources, interprocess communications have to be used such as pipes, files, sockets etc. See more on Linux process. Process provides each program with two key abstractions: 1. Logical control flow : Each process seems to have exclusive use of the CPU 2. Private virtual address space: Each process have exclusive use of main memory. A thread uses the same address space of a process. A process can have multiple threads. A key difference between processes and threads is that multiple threads share parts of their state. Typically, multiple threads can read from and write to the same memory (no process can directly access the memory of another process). However, each thread still has its own stack of activation records and its own copy of CPU registers, including the stack pointer and the program counter, which together describe the state of the thread's execution. A thread is a particular execution path of a process. When one thread modifies a process resource, the change is immediately visible to sibling threads. Processes are independent while thread is within a process. Processes have separate address spaces while threads share their address spaces. Multithreading has some advantages over multiple processes. Threads require less overhead to manage than processes, and intraprocess thread communication is less expensive than interprocess communication. Multiple concurrent programs can execute on a different machines. Examples are file servers (NFS), file transfer clients and servers (FTP), remote log-in clients and servers (Telnet), and Web browsers and servers. Multiprocessing A process is the unit of resource allocation & protection. A process manages certain resources, e.g., virtual memory, I/O handlers, and signal handlers. Multithreading A thread is the unit of computation that runs in the context of a process. A thread manages certain resources, e.g., stack, registers, signal masks, priorities, and thread-specific data Context Switch Switching the CPU from one process or thread to another is called context switch. It requires saving the state of the old process or thread and loading the state of the new one. Since there may be several hundred context switches per second, context switches can potentially add significant overhead to an execution. Context switch is implemented using exception control

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 3

flow. POSIX Threads The pthread library can be found on almost any modern POSIX-compliant OS (under Windows - http://sourceware.org/pthreads-win32/ ). There are a few required steps you need to take before starting any pthreads coding: 1. Add #include to your source file(s). 2. If you are using gcc, you can simply specify -pthread which will set all link-time libraries. 3. A pthread is represented by the type pthread_t. To create, terminate and suspend the thread, following functions are available: pthread_create(): creates the thread pthread_exit(): terminates the thread pthread_join(): Suspends the thread to wait for successful termination of thread. (Fig. 8.1).

Figure 8.1 Example 1: Independent threads In this example, threads displays strings: Hello and How are you, independent of each other. #include #include #include void * thread1() { while(1){ printf("Hello!!\n"); } } void * thread2() { while(1){ printf("How are you?\n"); } } int main() { int status; pthread_t tid1,tid2; pthread_create(&tid1,NULL,thread1,NULL); pthread_create(&tid2,NULL,thread2,NULL); pthread_join(tid1,NULL); Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 4

pthread_join(tid2,NULL); return 0; } Now compile this program (Note the -l option is to load the pthread library) $ gcc Lab8RollNoEx01.c -o Lab8RollNoEx01.o -lpthread On running, you can see many interleaved “Hello!!” and “How are you?” messages Example 2: Reader and Writer threads This example involves a reader and a writer thread. The reader thread reads a string from the user and writer //thread displays it. This program uses semaphore so as to achieve synchronization #include #include #include #include char n[1024]; sem_t len; void * read1() { while(1){ printf("Enter a string \n"); scanf("%s",n); sem_post(&len); } } void * write1() { while(1){ sem_wait(&len); printf("The string entered is :"); printf("==== %s\n",n); } } int main() { int status; pthread_t tr, tw; pthread_create(&tr,NULL,read1,NULL); pthread_create(&tw,NULL,write1,NULL); pthread_join(tr,NULL); pthread_join(tw,NULL); return 0; } Now compile this program (Note the -l option is to load the pthread library)

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 5

$ gcc Lab8RollNoEx02.c -o Lab8RollNoEx02.o -lpthread

Example 3: Reader and Writer threads with a delay in writer thread. But suppose we insert a sleep function() in write1 like void * write1() { while(1){ sleep(5); sem_wait(&len); printf("The string entered is :"); printf("==== %s\n",n); } } Here is the result:

Thread1 reads one more string but thread2 displays the last read string. Hence, we may need to use the condition variables to achieve serial read and write. Example 4: Threads with searial read / write, (condition variables and mutex locking) This example, involves reader & writer threads, but uses condition variables for serialization. #include #include #include #include #define TRUE 1 #define FALSE 0 char n[1024]; pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER; int string_read=FALSE; pthread_cond_t cond; void * read1() {

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 6

while(1){ while(string_read); pthread_mutex_lock(&lock); printf("Enter a string: \n"); scanf("%s",n); string_read=TRUE; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); } } void * write1() { while(1){ pthread_mutex_lock(&lock); while(!string_read) pthread_cond_wait(&cond,&lock); printf("The string entered is %s\n",n); string_read=FALSE; pthread_mutex_unlock(&lock); } } int main() { int status; pthread_t tr, tw; pthread_create(&tr,NULL,read1,NULL); pthread_create(&tw,NULL,write1,NULL); pthread_join(tr,NULL); pthread_join(tw,NULL); return 0; } Here is the output:

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 7

Exercises 1. Modify Example 1 to display strings via two independent threads: thread1: “Hello ! StudentName”, thread 2: “Student roll no is : 14B001BS” 2. Modify Example 2 to to read your roll number in reader thread, and display your roll number in writer thread: Thread1: “Enter your roll no”, Thread 2: “your roll no is 14B001BS”. 3. Modify Example 3 to read roll numbers in reader thread in an array, and display roll number in writer thread, and delay the writer thread by 30 seconds. Simulate the program by entering your roll number and 2 numbers after your roll number. E.g., If your roll number is 14B001BS, sample output should be like: 14b001BS@SUSE11-1:~/ 14b001BSLab8> ./14B001BSLab08Taks03.o Enter roll number [1]: 14b001BS Enter roll number [2]: 14B002BS Enter roll number [3]: 14B003BS Enter roll number [1]: 14b004BS Enter roll number [2]: 14B005BS Enter roll number [3]: 14B006BS Enter roll number: Roll No. entered [1]: 14B004BS Roll No. entered [2]: 14B005BS Roll No. entered [3]: 14B006BS

4. Modify Example 4 to read 3 roll numbers in reader thread in a global array. In writer thread display the same 3 elements of global array (i.e., 3 roll numbers). Simulate the program by entering your roll numbers, and 2 numbers after your roll number. E.g., If your roll number is 14B001BS, sample output should be like: 14b001BS@SUSE11-1:~/ 14b001BSLab8> ./14B001BSLab08Taks04.o Enter roll number [1]: 14b001BS Enter roll number [2]: 14B002BS Enter roll number [3]: 14B003BS Roll No. entered [1]: 14B001BS Roll No. entered [2]: 14B002BS Roll No. entered [3]: 14B003BS Enter roll number [1]: 14b004BS Enter roll number [2]: 14B005BS Enter roll number [3]: 14B006BS Roll No. entered [1]: 14B004BS Roll No. entered [2]: 14B005BS Roll No. entered [3]: 14B006BS

Note: (1) Create RollNoLabNo Dir in “/home/your account/” and create files using the convention: rollno-task01.c (source code), rollno-task01.o (binary file) E.g, 14b001bs -task01.c, 14b001bs -tast02.c, … 14b001bs –task05.c (2) With each task, attach : a. Screenshot of source code (vi terminal window), b. Screenshot of commands issued on terminal, and their respective results.

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems

Operating Systems: Multithreading | Page 8

c. Task observations in your own words. (at least, 3-4 lines of explanation) (3) Email all lab results / observations document and source code in zip format to the following email address: [email protected] a. Subject of Email : LabNoXX_Name_RollNo_Section Attachment name: LabNoXX_Name_RollNo_Section.zip (4) Email should be send during the lab timings on same day. Delayed Emails will not be considered for assessment. (5) Hard copies of Lab manual & observation should be provided during the lab timings on same day. Delayed print copies will not be considered for assessment.

Lab Instructor: Asst. Prof. Engr. Abdul-Rahman Mahmood, Course: CS-311 Operating Systems