Lecture 8. Introduction to Python! Lecture 8

Size: px
Start display at page:

Download "Lecture 8. Introduction to Python! Lecture 8"

Transcription

1 Lecture 8 Introduction to Python Lecture 8

2 Summary Python exceptions Processes and Threads Programming with Threads

3 Python Exceptions In Python, there are two distinguishable kinds of errors: syntax errors and exceptions. Syntax errors are usually called parsing errors. Exceptions are events that can modify the flow of control through a program. Python triggers exceptions automatically on errors, after that they can be intercepted and processed by the program, or can be thrown up to the calling methods. Exceptions allow jumping directly to a routine/handler which can process the unexpected occurred event

4 Exception roles Error handling Event notification Special case handling Termination actions Unusual flow control

5 Statements processing exceptions try/except Catch and recover from exceptions raised by Python, or by you. try/finally Perform cleanup actions, whether exceptions occur or not. raise Trigger an exception manually in your code. assert Conditionally trigger an exception in your code. with/as Implement context managers in Python 2.6 and 3.0 (optional in 2.5)

6 The general format of the try statement try: <statements> except <name1>: <statements> except (name2, name3): <statements> except <name4> as <data>: <statements> except: <statements> else: <statements> # Run this main action first # Run if name1 is raised during try block # Run if any of these exceptions occur # Run if name4 is raised, and get instance raised # Run for all (other) exceptions raised # Run if no exception was raised during try block

7 try statement clauses Clause Comments except: except name: except name as value: except (name1, name2): except (name1, name2) as value: else: finally: Catch all (or all other) exception types Catch a specific exception only Catch the listed exception and its instance Catch any of the listed exceptions Catch any listed exception and its instance Run if no exceptions are raised Always perform this block

8 Catching an exception def getatindex(str, idx): return str[idx] print(getatindex("python", 7)) print("statement after catching exception...") Output: Traceback (most recent call last): File "exception-1.py", line 5, in <module> print(getatindex("python", 7)) File "exception-1.py", line 2, in getatindex return str[idx] IndexError: string index out of range Notice that the statement after the function call is never executed Catching the exception def getatindex(str, idx): return str[idx] try: print(getatindex("python", 7)) except IndexError: print("exception occurred ) print("statement after catching exception...") Output: Exception occurred Statement after catching exception... After handling the exception, the execution of the program is resumed

9 Raising an exception def getatindex(str, idx): if idx > len(str): raise IndexError return str[idx] try: print(getatindex("python", 7)) except IndexError: print("exception occurred ) print("statement after catching exception...") Output: Exception occurred Statement after catching exception... One can raise exceptions using the assert directive too: def assert_fct(x): assert x = 0 print(x) assert_fct(0) Output: Traceback (most recent call last): File "exception-5.py", line 5, in <module> assert_fct(0) File "exception-5.py", line 2, in assert_fct assert x = 0 AssertionError

10 Creating a custom exception class CustomException(Exception): def str (self): return "CustomException representation..." def getatindex(str, idx): if idx > len(str): raise CustomException return str[idx] try: print(getatindex("python", 7)) except CustomException as e: print("exception occurred {}".format(e)) Output: Exception occurred CustomException representation...

11 Custom exceptions The recommended mode for creating custom exceptions is by using OOP, using classes and classes hierarchies. The most important advantages of using class-based exceptions are: They can be organized in categories (adding future categories will not require changes in the try block) They have state information attached They support inheritance

12 Termination Actions Let s suppose we need to deal with a file, open it, do some processing, then close it class MyException(Exception): pass def process_file(file): raise MyException try: f = open("../lab3/morse.txt", "r") process_file(f) print("after file processing...") finally: f.close() print("finally statement reached...") Output: finally statement reached... File "exception-4.py", line 9, in <module> process_file(f) File "exception-4.py", line 5, in process_file raise MyException main.myexception The try/finally construction assures that the statements included in the finally block are executed regardless of what happens in the try block This is extremely useful when we involve various resources in our program and we have to release them regardless of what events could occur during the execution of the program flow

13 Unified try/except/finally class MyException(Exception): def str (self): return "MyException" def process_file(file): raise MyException try: f = open("../lab3/morse.txt", "r") process_file(f) print("after file processing...") except MyException as me: print("exception occurred {}".format(me)) finally: f.close() print("finally statement reached...") Output: Exception occurred MyException finally statement reached... In this case, the exception raised in process_file() function is caught and processed in the exception handler defined in the except block, then the code defined in finally section is executed. In this way we assure ourselves that we release all the resources that we used during the program (file handlers, connections to databases, sockets, etc )

14 C vs. Python error handling C style Python style dostuff() { if (dofirstthing() == ERROR) return ERROR; if (donextthing() == ERROR) return ERROR;... return dolastthing(); } main() { if (dostuff() == ERROR) badending(); else goodending(); } def dostuff(): dofirstthing() donextthing()... dolastthing() if name == ' main ': try: dostuff() except: badending() else: goodending()

15 Processes and Threads Processes and Threads

16 Processes context switching How multiple processes share a CPU (image from 2 states for processes: Run Sleep PCB - Program Context Block

17 Relation between threads and processes [image taken from

18 Python Threads A Thread or a Thread of Execution is defined in computer science as the smallest unit that can be scheduled in an operating system. There are two different kind of threads: Kernel threads User-space Threads or user threads (image from

19 Threads Every process has at least one thread, i.e. the process itself. A process can start multiple threads. The operating system executes these threads like parallel "processes". On a single processor machine, this parallelism is achieved by thread scheduling or timeslicing. Advantages of Threading: Multithreaded programs can run faster on computer systems with multiple CPUs, because theses threads can be executed truly concurrent. A program can remain responsive to input. This is true both on single and on multiple CPU Threads of a process can share the memory of global variables. If a global variable is changed in one thread, this change is valid for all threads. A thread can have local variables.

20 Threads in Python Python has a Global Interpreter Lock (GIL) It imposes various restrictions on threads, one of the most important is that it cannot utilize multiple CPUs Consider the following piece of code: def count(n): while n > 0: n -= 1 Two scenarios: Run it twice in series: count( ) count( ) Now, run it in parallel in two threads t1 = Thread(target=count,args=( ,)) t1.start() t2 = Thread(target=count,args=( ,)) t2.start() t1.join(); t2.join() Some performance results on a Dual-Core MacBook? Sequential : 24.6s Threaded : 45.5s (1.8X slower) And if disabled one of the CPU cores, why does the threaded performance get better? Threaded : 38.0s

21 Python Threads Thread-Specific State Each thread has its own interpreter specific data structure (PyThreadState) Current stack frame (for Python code) Current recursion depth Thread ID Some per-thread exception information Optional tracing/profiling/debugging hooks It's a small C structure (<100 bytes) The interpreter has a global variable that simply points to the ThreadState structure of the currently running thread

22 Python Threads Only one Python thread can execute in the interpreter at once There is a "global interpreter lock" that carefully controls thread execution The GIL ensures that sure each thread get exclusive access to the interpreter internals when it's running (and that call-outs to C extensions play nice)

23 Using _thread package import _thread def print_chars(thread_name, char): for i in range(5): print("{} {}".format(thread_name, i * char)) print("{} successfully ended".format(thread_name)) try: print("starting main program...") _thread.start_new_thread(print_chars, ("Thread1 ", "*")) _thread.start_new_thread(print_chars, ("Thread2 ", "-")) _thread.start_new_thread(print_chars, ("Thread3 ", "=")) print("ending main program...") except: print("threads are unable to start") while 1: pass Starting main program... Ending main program... Thread2 Thread2 - Thread2 -- Thread2 --- Thread Thread2 successfully ended Thread3 Thread3 = Thread3 == Thread3 === Thread1 Thread1 * Thread1 ** Thread1 *** Thread1 **** Thread1 successfully ended Thread3 ==== Thread3 successfully ended _thread is a deprecated module, acting at low-level. _thread.start_new_thread method was used here to start a new thread. One can notice here that we have a while loop in the main program, looping forever. This is to avoid the situation in which the main program starts the three threads, but it exists before the threads finish their execution, and the buffers are not flushed (the output is buffered by default) See the program output and notice that the threads output is displayed after the main program end its execution.

24 First threading program import threading class ThreadExample(threading.Thread): def init (self, name, char): threading.thread. init (self) self.name = name self.char = char def run(self): print("starting thread {} ".format(self.name)) print_chars(self.name, self.char) print("ending thread {} ".format(self.name)) def print_chars(thread_name, char): for i in range(5): print("{} {}".format(thread_name, i * char)) if name == " main ": thread_one = ThreadExample("Thread1", "*") thread_two = ThreadExample("Thread2", "-") thread_three = ThreadExample("Thread3", "=") thread_one.start() thread_two.start() thread_three.start() print("exiting the main program...") Starting thread Thread1 Thread1 Thread1 * Thread1 ** Thread1 *** Thread1 **** Ending thread Thread1 Starting thread Thread2 Thread2 Thread2 - Thread2 -- Thread2 --- Thread Ending thread Thread2 Starting thread Thread3 Exiting the main program... Thread3 Thread3 = Thread3 == Thread3 === Thread3 ==== Ending thread Thread3? What happened here?

25 Using join() import threading class ThreadExample(threading.Thread): def init (self, name, char): threading.thread. init (self) self.name = name self.char = char def run(self): print("starting thread {} ".format(self.name)) print_chars(self.name, self.char) print("ending thread {} ".format(self.name)) def print_chars(thread_name, char): for i in range(5): print("{} {}".format(thread_name, i * char)) if name == " main ": thread_one = ThreadExample("Thread1", "*") thread_two = ThreadExample("Thread2", "-") thread_three = ThreadExample("Thread3", "=") thread_one.start() thread_two.start() thread_three.start() thread_one.join() thread_two.join() thread_three.join() print("exiting the main program...") Starting thread Thread1 Thread1 Thread1 * Thread1 ** Thread1 *** Thread1 **** Ending thread Thread1 Starting thread Thread2 Thread2 Thread2 - Thread2 -- Thread2 --- Thread Ending thread Thread2 Starting thread Thread3 Thread3 Thread3 = Thread3 == Thread3 === Thread3 ==== Ending thread Thread3 Exiting the main program... Note that now the main program ends AFTER all the threads finish

26 Determining current thread import threading import random class ThreadExample(threading.Thread): def init (self, name = None, char = '+'): threading.thread. init (self) if name is None: name = 'Thread' + str(random.randint(1, 100)) else: self.name = name self.char = char def run(self): print("starting thread {} ".format(self.name)) print_chars(threading.current_thread().getname(), self.char) print("ending thread {} ".format(self.name)) def print_chars(thread_name, char): for i in range(5): print("{} {}".format(thread_name, i * char)) if name == " main ": thread_one = ThreadExample(char = "*") thread_two = ThreadExample(char = "-") thread_three = ThreadExample(char = "=") thread_one.start() thread_two.start() thread_three.start() thread_one.join() thread_two.join() thread_three.join() print("exiting the main program...") Starting thread Thread-1 Thread-1 Thread-1 * Thread-1 ** Thread-1 *** Thread-1 **** Ending thread Thread-1 Starting thread Thread-2 Thread-2 Thread-2 - Thread-2 -- Thread Thread Ending thread Thread-2 Starting thread Thread-3 Thread-3 Thread-3 = Thread-3 == Thread-3 === Thread-3 ==== Ending thread Thread-3 Exiting the main program...

27 Thread synchronization Thread synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as critical section.

28 Synchronizing threads 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) print_time(self.name, self.counter, 3) def print_time(threadname, delay, counter): while counter: time.sleep(delay) print ("%s: %s" % (threadname, time.ctime(time.time()))) counter -= 1 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") We want to print some info about the running threads, first the info about one thread, then the info about a second thread. But, wait What happens with the output? The print result is scrambled between threads Not really what we wanted, right? Output: Starting Thread-1 Starting Thread-2 Thread-1: Thu Nov 24 18:20: Thread-2: Thu Nov 24 18:20: Thread-1: Thu Nov 24 18:20: Thread-1: Thu Nov 24 18:20: Thread-2: Thu Nov 24 18:20: Thread-2: Thu Nov 24 18:20: Exiting Main Thread

29 Synchronizing threads 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 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") This time one can see that the output looks much better. critical section Output: Starting Thread-1 Starting Thread-2 Thread-1: Thu Nov 24 18:26: Thread-1: Thu Nov 24 18:27: Thread-1: Thu Nov 24 18:27: Thread-2: Thu Nov 24 18:27: Thread-2: Thu Nov 24 18:27: Thread-2: Thu Nov 24 18:27: Exiting Main Thread

30 Queue data structure A queue is an abstract data structure, open at both ends. One of the ends is always used to insert data in the structure, while the other end is used to extract data fro the structure. The data insertion operation is called enqueueing, while the extraction of the data from the queue is called dequeueing.

31 Multithread Queues in Python The Queue module provides a FIFO implementation suitable for multithreaded programming. It can be used to pass messages or other data between producer and consumer threads safely. Locking is handled for the caller, so it is simple to have as many threads as you want working with the same Queue instance. 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.

32 Multithread Queues 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) 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 # Wait for all threads to complete for t in threads: t.join() print ("Exiting Main Thread") 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-3 processing Five Exiting Thread-1 Exiting Thread-2 Exiting Thread-3 Exiting Main Thread

33 References Mark Lutz - Learning Python, O Reilly Queue A thread-safe FIFO implementationhttps://pymotw.com/2/ Queue/ Python 3 - Multithreaded programming Inside the Python GIL - Operating System Tutorial - operating_system/os_process_scheduling.html

PYTHON MULTITHREADED PROGRAMMING

PYTHON MULTITHREADED PROGRAMMING PYTHON MULTITHREADED PROGRAMMING http://www.tutorialspoint.com/python/python_multithreading.htm Copyright tutorialspoint.com Running several threads is similar to running several different programs concurrently,

More information

Some examples of where it is useful to implement threads, even on single-core computers, are:

Some examples of where it is useful to implement threads, even on single-core computers, are: Chapter 7 Threading 7.1 Threading Threads are the smallest program units that an operating system can execute. Programming with threads allows that several lightweight processes can run simultaneously

More information

Lecture 9. Introduction to Python! Lecture 9

Lecture 9. Introduction to Python! Lecture 9 Lecture 9 Introduction to Python Lecture 9 Lecture 9 Summary Threads Daemons Timer Event Reentrant Locks Producer-Consumer problem Condition Semaphores Design Patterns Singleton Façade Factory Proxy Adapter

More information

Threading the Code. Self-Review Questions. Self-review 11.1 What is a thread and what is a process? What is the difference between the two?

Threading the Code. Self-Review Questions. Self-review 11.1 What is a thread and what is a process? What is the difference between the two? Threading the Code 11 Self-Review Questions Self-review 11.1 What is a thread and what is a process? What is the difference between the two? Self-review 11.2 What does the scheduler in an operating system

More information

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Abstract Data Types Chapter 1

Abstract Data Types Chapter 1 Abstract Data Types Chapter 1 Part Two Bags A bag is a basic container like a shopping bag that can be used to store collections. There are several variations: simple bag grab bag counting bag 2 Bag ADT

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Fasteners Documentation

Fasteners Documentation Fasteners Documentation Release 0.14.1 Joshua Harlow Jul 12, 2017 Contents 1 Lock 3 1.1 Classes.................................................. 3 1.2 Decorators................................................

More information

Multithreading. processes and threads life cycle of a thread. the thread module the Thread class. two different algorithms run concurrently

Multithreading. processes and threads life cycle of a thread. the thread module the Thread class. two different algorithms run concurrently Multithreading 1 Concurrent Processes processes and threads life cycle of a thread 2 Multithreading in Python the thread module the Thread class 3 Producer/Consumer Relation two different algorithms run

More information

The Kernel Abstraction

The Kernel Abstraction The Kernel Abstraction Debugging as Engineering Much of your time in this course will be spent debugging In industry, 50% of software dev is debugging Even more for kernel development How do you reduce

More information

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Shrideep Pallickara Computer Science Colorado State University L6.1 Frequently asked questions from the previous class survey L6.2 SLIDES CREATED BY:

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] The House of Heap and Stacks Stacks clean up after themselves But over deep recursions they fret The cheerful heap has nary a care Harboring memory

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

Computer architecture. A simplified model

Computer architecture. A simplified model Computer architecture A simplified model Computers architecture One (or several) CPU(s) Main memory A set of devices (peripherals) Interrupts Direct memory access Computers architecture Memory Keyboard

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

wait with priority An enhanced version of the wait operation accepts an optional priority argument: wait with priority An enhanced version of the wait operation accepts an optional priority argument: syntax: .wait the smaller the value of the parameter, the highest the priority

More information

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik Advanced Programming C# Lecture 13 dr inż. Małgorzata Janik majanik@if.pw.edu.pl Winter Semester 2017/2018 Project C# 2017/2018, Lecture 13 3 / 24 Project part III Final Date: 22.01.2018 (next week!) Today

More information

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message.

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message. What is CGI? The Common Gateway Interface (CGI) is a set of standards that define how information is exchanged between the web server and a custom script. is a standard for external gateway programs to

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

Asynchronous Programming Under the Hood. Week 6

Asynchronous Programming Under the Hood. Week 6 Asynchronous Programming Under the Hood Week 6 How to Implement Event Dispatchers Recall: Record registered callbacks in a data structure (easy) Wait for an event to happen (easy) Call the callbacks when

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Graphical User Interfaces Robert Rand University of Pennsylvania December 03, 2015 Robert Rand (University of Pennsylvania) CIS 192 December 03, 2015 1 / 21 Outline 1 Performance

More information

Processes and Threads

Processes and Threads COS 318: Operating Systems Processes and Threads Kai Li and Andy Bavier Computer Science Department Princeton University http://www.cs.princeton.edu/courses/archive/fall13/cos318 Today s Topics u Concurrency

More information

The control of I/O devices is a major concern for OS designers

The control of I/O devices is a major concern for OS designers Lecture Overview I/O devices I/O hardware Interrupts Direct memory access Device dimensions Device drivers Kernel I/O subsystem Operating Systems - June 26, 2001 I/O Device Issues The control of I/O devices

More information

Lecture 15: I/O Devices & Drivers

Lecture 15: I/O Devices & Drivers CS 422/522 Design & Implementation of Operating Systems Lecture 15: I/O Devices & Drivers Zhong Shao Dept. of Computer Science Yale University Acknowledgement: some slides are taken from previous versions

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

More information

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik Advanced Programming C# Lecture 12 dr inż. Małgorzata Janik malgorzata.janik@pw.edu.pl Winter Semester 2018/2019 Project Project part III Final Date: 22.01.2018 (next week!) Presentations (max 5 min per

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Review 3. Exceptions and Try-Except Blocks

Review 3. Exceptions and Try-Except Blocks Review 3 Exceptions and Try-Except Blocks What Might You Be Asked Create your own Exception class Write code to throw an exception Follow the path of a thrown exception Requires understanding of try-except

More information

Structure and Flow. CS 3270 Chapter 5

Structure and Flow. CS 3270 Chapter 5 Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Advanced Flow of Control -- Introduction

Advanced Flow of Control -- Introduction Advanced Flow of Control -- Introduction Two additional mechanisms for controlling process execution are exceptions and threads Chapter 14 focuses on: exception processing catching and handling exceptions

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

ECE 391 Exam 1 Review Session - Spring Brought to you by HKN

ECE 391 Exam 1 Review Session - Spring Brought to you by HKN ECE 391 Exam 1 Review Session - Spring 2018 Brought to you by HKN DISCLAIMER There is A LOT (like a LOT) of information that can be tested for on the exam, and by the nature of the course you never really

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Python for Astronomers. Errors and Exceptions

Python for Astronomers. Errors and Exceptions Python for Astronomers Errors and Exceptions Exercise Create a module textstat that contains the functions openfile(filename, readwrite=false): opens the specified file (readonly or readwrite) and returns

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher')

More information

The Kernel Abstraction. Chapter 2 OSPP Part I

The Kernel Abstraction. Chapter 2 OSPP Part I The Kernel Abstraction Chapter 2 OSPP Part I Kernel The software component that controls the hardware directly, and implements the core privileged OS functions. Modern hardware has features that allow

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

연세대학교전기전자공학과프로세서연구실박사과정김재억.

연세대학교전기전자공학과프로세서연구실박사과정김재억. 이강좌는연세대학교이용석교수연구실에서제작되었으며 copyright가없으므로비영리적인목적에한하여누구든지복사, 배포가가능합니다. 연구실홈페이지에는 고성능마이크로프로세서에관련된많은강의가있으며누구나무료로다운로드받을 수있습니다. 연세대학교전기전자공학과프로세서연구실박사과정김재억 Email: yonglee@yonsei.ac.kr 멀티스레드프로그래밍 (Multithreaded

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

LET ME SLEEP ON IT. Improving concurrency in unexpected ways. Nir Soffer PyCon Israel 2017

LET ME SLEEP ON IT. Improving concurrency in unexpected ways. Nir Soffer PyCon Israel 2017 LET ME SLEEP ON IT Improving concurrency in unexpected ways Nir Soffer PyCon Israel 2017 $ whoami Taming the Vdsm beast since 2013 Tinkering with Python since 2003 Free software enthusiast

More information

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2 Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented

More information

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

Dr. Rafiq Zakaria Campus. Maulana Azad College of Arts, Science & Commerce, Aurangabad. Department of Computer Science. Academic Year

Dr. Rafiq Zakaria Campus. Maulana Azad College of Arts, Science & Commerce, Aurangabad. Department of Computer Science. Academic Year Dr. Rafiq Zakaria Campus Maulana Azad College of Arts, Science & Commerce, Aurangabad Department of Computer Science Academic Year 2015-16 MCQs on Operating System Sem.-II 1.What is operating system? a)

More information

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

More information

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

Last 2 Classes: Introduction to Operating Systems & C++ tutorial. Today: OS and Computer Architecture

Last 2 Classes: Introduction to Operating Systems & C++ tutorial. Today: OS and Computer Architecture Last 2 Classes: Introduction to Operating Systems & C++ tutorial User apps OS Virtual machine interface hardware physical machine interface An operating system is the interface between the user and the

More information

Networking, Java threads and synchronization. PRIS lecture 4 Fredrik Kilander

Networking, Java threads and synchronization. PRIS lecture 4 Fredrik Kilander Networking, Java threads and synchronization PRIS lecture 4 Fredrik Kilander OSI Application Presentation Session Transport Network Data link Physical TCP/IP Application Transport Internet Host-to-network

More information

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources Thread-Local Lecture 27: Concurrency 3 CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Some slides based on those from Dan Grossman, U. of Washington Whenever possible, don t share resources Easier to have

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

More information

DAD Lab. 2 Additional C# Topics

DAD Lab. 2 Additional C# Topics DAD 2017-2018 Lab. 2 Additional C# Topics Summary 1. Properties 2. Exceptions 3. Delegates and events 4. Generics 5. Threads and synchronization 1. Properties Get/Set Properties Simple way to control the

More information

National University. Faculty of Computer Since and Technology Object Oriented Programming

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

CSC369 Lecture 2. Larry Zhang

CSC369 Lecture 2. Larry Zhang CSC369 Lecture 2 Larry Zhang 1 Announcements Lecture slides Midterm timing issue Assignment 1 will be out soon! Start early, and ask questions. We will have bonus for groups that finish early. 2 Assignment

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

CSC369 Lecture 2. Larry Zhang, September 21, 2015

CSC369 Lecture 2. Larry Zhang, September 21, 2015 CSC369 Lecture 2 Larry Zhang, September 21, 2015 1 Volunteer note-taker needed by accessibility service see announcement on Piazza for details 2 Change to office hour to resolve conflict with CSC373 lecture

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Operating Systems (1DT020 & 1TT802)

Operating Systems (1DT020 & 1TT802) Uppsala University Department of Information Technology Name: Perso. no: Operating Systems (1DT020 & 1TT802) 2009-05-27 This is a closed book exam. Calculators are not allowed. Answers should be written

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

POSIX Threads: a first step toward parallel programming. George Bosilca

POSIX Threads: a first step toward parallel programming. George Bosilca POSIX Threads: a first step toward parallel programming George Bosilca bosilca@icl.utk.edu Process vs. Thread A process is a collection of virtual memory space, code, data, and system resources. A thread

More information

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University Concurrent Programming Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University 1 Objectives You will learn/review: What a process is How to fork and wait for processes What a thread is How to spawn

More information

Operating System Structure

Operating System Structure Operating System Structure CSCI 4061 Introduction to Operating Systems Applications Instructor: Abhishek Chandra Operating System Hardware 2 Questions Operating System Structure How does the OS manage

More information

CS533 Concepts of Operating Systems. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?

More information

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012 CMPSCI 187: Programming With Data Structures Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012 Concurrency and a Case Study Concurrency and Threads Example: Counter, Increase,

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

Chapter 14. Exception Handling and Event Handling

Chapter 14. Exception Handling and Event Handling Chapter 14 Exception Handling and Event Handling Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction to Event

More information

Administrivia. HW1 due Oct 4. Lectures now being recorded. I ll post URLs when available. Discussing Readings on Monday.

Administrivia. HW1 due Oct 4. Lectures now being recorded. I ll post URLs when available. Discussing Readings on Monday. Administrivia HW1 due Oct 4. Lectures now being recorded. I ll post URLs when available. Discussing Readings on Monday. Keep posting discussion on Piazza Python Multiprocessing Topics today: Multiprocessing

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole The Process Concept 2 The Process Concept Process a program in execution Program - description of how to perform an activity instructions and static

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

CS193k, Stanford Handout #8. Threads 3

CS193k, Stanford Handout #8. Threads 3 CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current

More information

Queues. Queue ADT Queue Implementation Priority Queues

Queues. Queue ADT Queue Implementation Priority Queues Queues Queue ADT Queue Implementation Priority Queues Queue A restricted access container that stores a linear collection. Very common for solving problems in computer science that require data to be processed

More information

Interrupts, Etc. Operating Systems In Depth V 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.

Interrupts, Etc. Operating Systems In Depth V 1 Copyright 2018 Thomas W. Doeppner. All rights reserved. Interrupts, Etc. Operating Systems In Depth V 1 Copyright 2018 Thomas W. Doeppner. All rights reserved. Interrupts User stack frames Kernel stack frames Interrupt handler 1 s frame Interrupt handler 2

More information

SMD149 - Operating Systems

SMD149 - Operating Systems SMD149 - Operating Systems Roland Parviainen November 3, 2005 1 / 45 Outline Overview 2 / 45 Process (tasks) are necessary for concurrency Instance of a program in execution Next invocation of the program

More information

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop()) Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully.

More information

Sample Questions. Amir H. Payberah. Amirkabir University of Technology (Tehran Polytechnic)

Sample Questions. Amir H. Payberah. Amirkabir University of Technology (Tehran Polytechnic) Sample Questions Amir H. Payberah amir@sics.se Amirkabir University of Technology (Tehran Polytechnic) Amir H. Payberah (Tehran Polytechnic) Sample Questions 1393/8/10 1 / 29 Question 1 Suppose a thread

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 4 Software design principles Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types

More information

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

More information

14. Exception Handling

14. Exception Handling 14. Exception Handling 14.1 Intro to Exception Handling In a language without exception handling When an exception occurs, control goes to the operating system, where a message is displayed and the program

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information