Sistem Operasi 2014-2015 © Sekolah Tinggi Teknik Surabaya 1.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Processes and Threads Chapter 3 and 4 Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee Community College,
How to Build Multi- threaded Applications in.NET Mazen S. Alzogbi Technology Specialist Microsoft Corporation.
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Chapter 6 Process Synchronization Bernard Chen Spring 2007.
Programming Robots Python-Threading. Programming Robots Thread vs Threading Python offers two thread modules  Thread: used up to now; including this.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Threading Part 4 CS221 – 4/27/09. The Final Date: 5/7 Time: 6pm Duration: 1hr 50mins Location: EPS 103 Bring: 1 sheet of paper, filled both sides with.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Multithreaded Programming in Python Nick Anastasia.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
Fundamentals of Python: From First Programs Through Data Structures
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Lecture 6 Threads Erick Pranata
Prepared by Oussama Jebbar
Multithreading / Concurrency
Threaded Programming in Python
Multithreading.
Multithreaded Programming in Java
Java Concurrency.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Concurrency.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Multithreading.
Multithreaded Programming
Threaded Programming in Python
21 Threads.
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Sistem Operasi © Sekolah Tinggi Teknik Surabaya 1

» Running several threads is similar to running several different programs concurrently, but with the following benefits: ˃Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. ˃Threads sometimes called light-weight processes and they do not require much memory overhead; they care cheaper than processes. 2 © Sekolah Tinggi Teknik Surabaya

» A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running. » It can be pre-empted (interrupted) » It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding. 3 © Sekolah Tinggi Teknik Surabaya

» To spawn another thread, you need to call following method available in thread module: thread.start_new_thread (function,args[,kwargs] ) » Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. » kwargs is an optional dictionary of keyword arguments. 4 © Sekolah Tinggi Teknik Surabaya

#!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass 5 © Sekolah Tinggi Teknik Surabaya

Thread-1: Thu Jan 22 15:42: Thread-1: Thu Jan 22 15:42: Thread-2: Thu Jan 22 15:42: Thread-1: Thu Jan 22 15:42: Thread-2: Thu Jan 22 15:42: Thread-1: Thu Jan 22 15:42: Thread-1: Thu Jan 22 15:42: Thread-2: Thu Jan 22 15:42: Thread-2: Thu Jan 22 15:42: Thread-2: Thu Jan 22 15:42: © Sekolah Tinggi Teknik Surabaya

» The threading module exposes all the methods of the thread module and provides some additional methods: ˃threading.activeCount(): Returns the number of thread objects that are active. ˃threading.currentThread(): Returns the number of thread objects in the caller's thread control. ˃threading.enumerate(): Returns a list of all thread objects that are currently active. 7 © Sekolah Tinggi Teknik Surabaya

» In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows: ˃run(): The run() method is the entry point for a thread. ˃start(): The start() method starts a thread by calling the run method. ˃join([time]): The join() waits for threads to terminate. ˃isAlive(): The isAlive() method checks whether a thread is still executing. ˃getName(): The getName() method returns the name of a thread. ˃setName(): The setName() method sets the name of a thread. 8 © Sekolah Tinggi Teknik Surabaya

» To implement a new thread using the threading module, you have to do the following: ˃Define a new subclass of the Thread class. ˃Override the __init__(self [,args]) method to add additional arguments. ˃Then, override the run(self [,args]) method to implement what the thread should do when started. » Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which will in turn call run() method. 9 © Sekolah Tinggi Teknik Surabaya

#!/usr/bin/python import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name print "Exiting Main Thread" 10 © Sekolah Tinggi Teknik Surabaya

def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() 11 © Sekolah Tinggi Teknik Surabaya

Starting Thread-1 Starting Thread-2 Exiting Main Thread Thread-1: Thu Mar 21 09:10: Thread-1: Thu Mar 21 09:10: Thread-2: Thu Mar 21 09:10: Thread-1: Thu Mar 21 09:10: Thread-1: Thu Mar 21 09:10: Thread-2: Thu Mar 21 09:10: Thread-1: Thu Mar 21 09:10: Exiting Thread-1 Thread-2: Thu Mar 21 09:10: Thread-2: Thu Mar 21 09:10: Thread-2: Thu Mar 21 09:10: Exiting Thread-2 12 © Sekolah Tinggi Teknik Surabaya

» The threading module provided with Python includes a simple-to-implement locking mechanism that will allow you to synchronize threads. » A new lock is created by calling the Lock() method, which returns the new lock. » The acquire(blocking) method of the new lock object would be used to force threads to run synchronously. » The optional blocking parameter enables you to control whether the thread will wait to acquire the lock. 13 © Sekolah Tinggi Teknik Surabaya

» If blocking is set to 0, the thread will return immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. » If blocking is set to 1, the thread will block and wait for the lock to be released. » The release() method of the the new lock object would be used to release the lock when it is no longer required. 14 © Sekolah Tinggi Teknik Surabaya

#!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 15 © Sekolah Tinggi Teknik Surabaya

threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" 16 © Sekolah Tinggi Teknik Surabaya

Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11: Thread-1: Thu Mar 21 09:11: Thread-1: Thu Mar 21 09:11: Thread-2: Thu Mar 21 09:11: Thread-2: Thu Mar 21 09:11: Thread-2: Thu Mar 21 09:11: Exiting Main Thread 17 © Sekolah Tinggi Teknik Surabaya

» The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue: ˃get(): The get() removes and returns an item from the queue. ˃put(): The put adds item to a queue. ˃qsize() : The qsize() returns the number of items that are currently in the queue. ˃empty(): The empty( ) returns True if queue is empty; otherwise, False. ˃full(): the full() returns True if queue is full; otherwise, False. 18 © Sekolah Tinggi Teknik Surabaya

#!/usr/bin/python import Queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + self.name def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print "%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1) 19 © Sekolah Tinggi Teknik Surabaya

threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = Queue.Queue(10) threads = [] threadID = 1 # Create new threads for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queue queueLock.acquire() for word in nameList: workQueue.put(word) queueLock.release() # Wait for queue to empty while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 20 © Sekolah Tinggi Teknik Surabaya

# Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" 21 © Sekolah Tinggi Teknik Surabaya

Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Exiting Thread-3 Exiting Thread-1 Exiting Thread-2 Exiting Main Thread 22 © Sekolah Tinggi Teknik Surabaya

» python_multithreading.htm 23 © Sekolah Tinggi Teknik Surabaya

24 © Sekolah Tinggi Teknik Surabaya