Lecture 9. Introduction to Python! Lecture 9
|
|
- Daniel Skinner
- 6 years ago
- Views:
Transcription
1 Lecture 9 Introduction to Python Lecture 9
2 Lecture 9 Summary Threads Daemons Timer Event Reentrant Locks Producer-Consumer problem Condition Semaphores Design Patterns Singleton Façade Factory Proxy Adapter
3 Daemons import threading import time def do_something_non_daemonic(): print("starting non-daemonic...") print("ending non-daemonic...") def do_something_daemonic(): print("starting daemonic...") time.sleep(5) print("ending non-daemonic...") t1 = threading.thread(name = "t1", target = do_something_non_daemonic) t2 = threading.thread(name = "t2", target = do_something_daemonic) t2.setdaemon(true) t1.start() t2.start() Output: starting non-daemonic... ending non-daemonic... starting daemonic... Process finished with exit code 0 Be sure to set the daemon flag for the thread before calling the start() method, otherwise you ll fall in a RuntimeError. It is not possible to alter that flag after the thread was started
4 Daemons A thread can be flagged as daemon thread, having the significance that the main program will exit only when no other threads than daemons are left running. Keep in mind that the daemons threads are abruptly stopped at shutdown. If they are using resources like connections, files, etc, they may not be properly released. Given all these, daemons are useful when, during the main runs, it is ok to kill them after all the other non-daemon threads have completed their work. Some examples of daemon threads are the ones for sending keepalive packets, running periodically garbage collection, and more. The threading.thread class has the following methods dealing with daemon threads: isdaemon() returns True if the current threads was flagged as being a daemon setdaemon() sets the daemon flag for the current thread
5 Enumerate threads import threading import random import time class MyThread(threading.Thread): def init (self): threading.thread. init (self) def run(self): name = threading.current_thread().getname() fun(name) def fun(name): k = random.randint(5, 10) print("sleeping {} seconds...".format(k)) time.sleep(k) print("ending sleep for {}".format(name)) if name == " main ": for i in range(5): t = MyThread(); t.start() main_thread = threading.current_thread() for j in threading.enumerate(): print("thread name {}".format(j.getname())) # we cannot join a thread to itself. Through the # threads returned by enumerate() # one can found the main thread too if j is not main_thread: j.join() Output: sleeping 6 seconds... sleeping 10 seconds... sleeping 8 seconds... sleeping 9 seconds... sleeping 6 seconds... Thread name MainThread Thread name Thread-1 ending sleep for Thread-1 Thread name Thread-2 ending sleep for Thread-5 ending sleep for Thread-3 ending sleep for Thread-4 ending sleep for Thread-2 Thread name Thread-4 Thread name Thread-5 Thread name Thread-3 enumerate() will gather all active threads, daemons or non-daemons, including the main thread. All the threads being in Alive state will be retrieved
6 Timer object import threading def func(time_interval): print("executed after {} seconds...".format(time_interval)) time_interval = 3 # seconds t = threading.timer(time_interval, func, [time_interval]) t.start() Executed after 3 seconds... Output When we need to execute a piece of code after a specific time interval, one can use the threading.timer object. Timer is a subclass of threading.thread class. The timer can be interrupted inside the interval by calling the cancel() method. Notice how we pass the arguments to the callback function func, in the threading.timer creation code
7 Events def wait_for_event(e): print("starting wait_for_event...") event_set = e.wait() print("in wait_for_event event_set is {}".format(event_set)) def wait_for_event_timeout(e, timeout): while not e.isset(): print("starting wait_for_event_timeout...") event_set = e.wait(timeout) print("in wait_for_event_timeout event_set is {}".format(event_set)) if event_set: print("processing event...") else: print("do something else...") if name == " main ": e = threading.event() t1 = threading.thread(name='blocking', target=wait_for_event, args=(e,)) t1.start() t2 = threading.thread(name='non_blocking', target=wait_for_event_timeout, args=(e, 3)) t2.start() print("before generating event...") time.sleep(3) e.set() print("after generating event...") One of the simplest mechanism of communication among threads is the one using the Event object. In this scenario, a thread signals an event, another thread is waiting for that event to occur. Internally, the Event object has a flag which is set using the set() method, or cleared using clear() method. The wait() method blocks the thread until the Event flag is set to true starting wait_for_event... starting wait_for_event_timeout... before generating event... in wait_for_event_timeout event_set is False do something else... starting wait_for_event_timeout... after generating event... in wait_for_event_timeout event_set is True processing event... in wait_for_event event_set is True
8 Reentrant locks import threading lock = threading.lock() print("acquiring lock first time {}".format(lock.acquire())) print("acquiring lock second time {}".format(lock.acquire(false))) print("this is displayed if the main thread is not blocked") Output: Acquiring lock first time True Acquiring lock second time False This is displayed if the main thread is not blocked A Lock object can be acquired only once, even if this is performed from the same thread. One can see from this example that the second attempt to acquire the lock will fail, the acquire() function is returning False. The call to the acquire() method was made by changing the default argument of the blocking parameter to False, meaning that the thread won t block until the lock will be released, but returning immediately with a result of False.
9 Reentrant locks import threading lock = threading.rlock() print("acquiring lock first time {}".format(lock.acquire())) print("acquiring lock second time {}".format(lock.acquire())) print("this is displayed if the main thread is not blocked") Output: Acquiring lock first time True Acquiring lock second time True This is displayed if the main thread is not blocked Changing the Lock object with a re-entrant lock object RLock will solve the problem of acquiring the lock multiple times by a thread. One can see that the result of acquire() method is True, which means that the lock was successfully acquired second time also. RLock object is useful in recursive functions where the code is executed multiple times.
10 The Producer-Consumer problem The producer-consumer problem is a well-known example of synchronization among multiple processes. It describes two distinct processes, one called producer and one called consumer, which share a common buffer, having a fixed size, used as a queue. The producer generates data and push it into the buffer, while the consumer consumes the data stored in the buffer, one piece at a time. One have to make sure that the producer won t try to add data in the buffer while it is full and the consumer won t try to remove data if the buffer is empty. The processes run simultaneously, so we have to synchronize them.
11 The Condition object A Condition object is always associated with a kind of lock. The condition object can be passed in or it can be created by default. The Condition object allows one or more threads to wait until notified by another thread. Being associated to a lock, it has acquire() and release() methods, no need for explicit Lock object. In the case of producer-consumer problem, the consumer needs to wait for a notification, using the instance of a Condition object, while the producer needs to notify the consumer using the same instance of Condition object. This means that the Condition instance will be passed between producer and consumer. On the next slide, a very simplified example of producer-consumer is explained.
12 The Condition object import threading import time def consumer(cond): print("starting the consumer thread {}...".format(threading.current_thread().getname())) with cond: print("consumer thread {} is waiting...".format(threading.current_thread().getname())) cond.wait() print("consumer thread {} consumed the resource...".format(threading.current_thread().getname())) def producer(cond): print("starting the producer thread {}...".format(threading.current_thread().getname())) with cond: print("producing a resource...") print("inform all the consumers about it...") cond.notifyall() if name == " main ": condition = threading.condition() consumer_one = threading.thread(name="consumer-one", target=consumer, args=(condition,)) consumer_two = threading.thread(name="consumer-two", target=consumer, args=(condition,)) producer_one = threading.thread(name="producer-one", target=producer, args=(condition,)) consumer_one.start() time.sleep(3) consumer_two.start() time.sleep(3) producer_one.start() Starting the consumer thread Consumer-One... Consumer thread Consumer-One is waiting... Starting the consumer thread Consumer-Two... Consumer thread Consumer-Two is waiting... Starting the producer thread Producer-One... Producing a resource... Inform all the consumers about it... Consumer thread Consumer-One consumed the resource... Consumer thread Consumer-Two consumed the resource...
13 Semaphores Semaphores are some of the oldest synchronization mechanisms. They were invented by Edsger W. Djikstra in 1962 or A Semaphore manages an internal counter which is decremented by each acquire() method and incremented by each release(). The counter can never go below zero. When acquire() finds that the counter reached zero, it block until another thread will call a release(). In contrast to the mutexes (or locks), semaphores allow many threads to run concurrently and access a resource, but in the same time they limit the overall number of accesses. Semaphores are useful when we need to support concurrent downloads, or concurrent connections to a web server or to a database, but also one can find other use cases, where concurrency is required.
14 Semaphores import threading import time class ThreadPool(): def init (self): self.active = [] self.lock = threading.lock() def makeactive(self, name): with self.lock: self.active.append(name) print("running {}".format(self.active)) def makeinactive(self, name): with self.lock: self.active.remove(name) print("running {}".format(self.active)) def func(s, pool): print("waiting to join the threading pool...") with s: name = threading.current_thread().getname() pool.makeactive(name) time.sleep(1) pool.makeinactive(name) if name == " main ": pool = ThreadPool() semaphore = threading.semaphore(5) for i in range(10): t = threading.thread(name="thread-" + str(i), target=func, args=(semaphore, pool)) t.start()
15 Semaphores The output from the previous slide Waiting to join the threading pool... Running ['Thread-0'] Waiting to join the threading pool... Running ['Thread-0', 'Thread-1'] Waiting to join the threading pool... Running ['Thread-0', 'Thread-1', 'Thread-2'] Waiting to join the threading pool... Running ['Thread-0', 'Thread-1', 'Thread-2', 'Thread-3'] Waiting to join the threading pool... Running ['Thread-0', 'Thread-1', 'Thread-2', 'Thread-3', 'Thread-4'] Waiting to join the threading pool... Waiting to join the threading pool... Waiting to join the threading pool... Waiting to join the threading pool... Waiting to join the threading pool... Running ['Thread-1', 'Thread-2', 'Thread-3', 'Thread-4'] Running ['Thread-2', 'Thread-3', 'Thread-4'] Running ['Thread-3', 'Thread-4'] Running ['Thread-3', 'Thread-4', 'Thread-5'] Running ['Thread-4', 'Thread-5'] Running ['Thread-5'] Running ['Thread-5', 'Thread-6'] Running ['Thread-5', 'Thread-6', 'Thread-7'] Running ['Thread-5', 'Thread-6', 'Thread-7', 'Thread-8'] Running ['Thread-5', 'Thread-6', 'Thread-7', 'Thread-8', 'Thread-9'] Running ['Thread-5', 'Thread-7', 'Thread-8', 'Thread-9'] Running ['Thread-7', 'Thread-8', 'Thread-9'] Running ['Thread-7', 'Thread-8'] Running ['Thread-7'] Running []
16 Design Patterns DESIGN PATTERNS
17 Singleton Design Pattern Singleton Design Pattern (aka Highlander) There can be only one In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton. (Wikipedia definition) The most popular use of the singleton is where we have objects that deal with things like controllers in MVC design pattern or database connections. Sometimes, resource creation can be very costly, so we limit it to a single instance that will be used again and again. The Singleton design pattern is a way that assures that a class will have one and only one instance.
18 Java Singleton version public class Singleton { private static Singleton instance = null; private Singleton(){ } Output: public static Singleton getinstance(){ if(instance == null){ instance = new Singleton(); } return instance; } public static void main(string[] args){ Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); } } System.out.println(s1.hashCode()); System.out.println(s2.hashCode());
19 Python Singleton version Version 1 class Singleton(): def new (cls, *args, **kwargs): if not hasattr(cls, '_inst'): cls._inst = super(singleton, cls). new (cls, *args, **kwargs) return cls._inst s1 = Singleton() print(id(s1)) s2 = Singleton() print(id(s2)) s3 = Singleton() print(id(s3)) Output:
20 Python Singleton Version Version 2 class Singleton(): instance = None def new (cls, *args, **kwargs): if Singleton.instance is None: Singleton.instance = object. new (cls, *args, **kwargs) return Singleton.instance def str (self): return self. class. name a = Singleton() print(id(a)) b = Singleton() print(id(b)) Output:
21 Façade Design Pattern Façade Design Pattern The façade pattern is a software engineering design pattern commonly used with Object-oriented programming. (The name is by analogy to an architectural facade.). A facade is an object that provides a simplified interface to a larger body of code, such as a class library. (Wikipedia definition) The façade pattern is a Structural Design Pattern, used to hide the complexity of a system, acting like a simplified interface to the client. This way, the client can easily deal with that interface, avoiding the complicated operation beneath.
22 Façade Design Pattern
23 Façade Design Pattern class VirtualCpu(object): def jump(self): print("{} jump to instruction".format(self. class. name )) def execute(self): print("{} executed the instruction".format(self. class. name )) class VirtualMemory(): def load(self): print("{} loaded the boot address in memory".format(self. class. name )) class VirtualHardDisk(): def read(self): print("{} read the boot sector from disk".format(self. class. name )) class VirtualMachine(): def start(self): virtual_cpu = VirtualCpu() virtual_memory = VirtualMemory() virtual_hard_disk = VirtualHardDisk() virtual_memory.load() virtual_hard_disk.read() virtual_cpu.jump() virtual_cpu.execute() virtual_machine = VirtualMachine() virtual_machine.start() VirtualMemory loaded the boot address in memory VirtualHardDisk read the boot sector from disk VirtualCpu jump to instruction VirtualCpu executed the instruction
24 Factory Design Pattern Factory Design Pattern The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects. (Wikipedia definition) In Factory design pattern we create objects in a way that avoids exposing the creation logic to the client. The newly created object is referred through a common interface. The common use cases for Factory design pattern are: When a class doesn t know what kind of objects will have to create When you have to create an object of anyone of subclasses, depending on the data provided
25 Factory Design Pattern
26 Factory Design Pattern class Soldier: def init (self, name): self.name = name def get_name(self): return self.name def str (self): return self. class. name class Swordsman(Soldier): def init (self, name): print("hi, I am {} and I am a {}".format(name, self. str ())) class Bowman(Soldier): def init (self, name): print("hi, I am {} and I am a {}".format(name, self. str ())) class Factory: def getsoldier(self, name, weapon): if weapon == 'BOW': return Bowman(name) elif weapon == 'SWORD': return Swordsman(name) if name == ' main ': s = Factory().getSoldier('John', 'SWORD') s = Factory().getSoldier('Richard', 'BOW') Hi, I am John and I am a Swordsman Hi, I am Richard and I am a Bowman
27 Proxy Design Pattern Proxy Design Pattern (Surrogate) A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. A well-known example of the proxy pattern is a reference counting pointer object. (Wikipedia definition) A Proxy pattern have three distinct and essential elements: The Real Subject (the real class performing all the business, but whose creation is costly) The Proxy Class, acting like an interface to user requests, shielding the Real Subject The Client, making the requests
28 Proxy Design Pattern Typical situation in which a Proxy pattern is recommended: Creation of the Real Subject object is costly in terms of resources, but creation of a Proxy is a cheaper option The Real Subject must be protected from direct use by its clients Sometimes one need to delay the creation of the Real Subject to the point it is really needed, using lazy initialization
29 Proxy Design Pattern
30 Proxy Design Pattern class Image(object): def display_image(self): raise NotImplementedError class RealImage(Image): def init (self, filename): self.filename = filename self.load_image_from_disk() def load_image_from_disk(self): print("loading {}".format(self.filename)) def display_image(self): print("displaying {}".format(self.filename)) class ProxyImage(Image): def init (self, filename): self.filename = filename self.real_image = None def display_image(self): if self.real_image is None: self.real_image = RealImage(self.filename) self.real_image.display_image() image1 = ProxyImage("photo_one") image2 = ProxyImage("photo_two") image1.display_image() image1.display_image() image2.display_image() image2.display_image() image1.display_image() Loading photo_one Displaying photo_one Displaying photo_one Loading photo_two Displaying photo_two Displaying photo_two Displaying photo_one
31 Adapter Design Pattern Adapter Design Pattern The Adapter pattern is a software design pattern (also known as Wrapper, an alternative naming shared with the Decorator pattern) that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. (Wikipedia definition) The Adapter makes possible to interconnect two different interfaces, making them work together.
32 Adapter Design Pattern
33 Adapter Design Pattern class Soldier(object): def who_am_i(self): raise NotImplementedError def fight(self): raise NotImplementedError class Swordsman(Soldier): def who_am_i(self): print("i am a swordsman") def fight(self): print("i am using a sword") class Cannon(object): def make_boom(self): print("boom") class SoldierAdapter(object): def init (self, cannon): self.cannon = cannon def fight(self): self.cannon.make_boom() if name == " main ": swordsman = Swordsman() swordsman.fight() cannon = Cannon() soldier_adapter = SoldierAdapter(cannon) soldier_adapter.fight() Output: I am using a sword BOOM
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 informationSome 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 informationLecture 8. Introduction to Python! Lecture 8
Lecture 8 Introduction to Python Lecture 8 Summary Python exceptions Processes and Threads Programming with Threads Python Exceptions In Python, there are two distinguishable kinds of errors: syntax errors
More informationFasteners Documentation
Fasteners Documentation Release 0.14.1 Joshua Harlow Jul 12, 2017 Contents 1 Lock 3 1.1 Classes.................................................. 3 1.2 Decorators................................................
More informationThreading 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 informationThe Singleton Pattern. Design Patterns In Java Bob Tarr
The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,
More informationCGI 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 informationLecture 8: September 30
CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate
More informationAsynchronous 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 informationThe Strategy Pattern Design Principle: Design Principle: Design Principle:
Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design
More informationMultitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit
Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking
More informationContents. 6-1 Copyright (c) N. Afshartous
Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004
More informationCmpSci 187: Programming with Data Structures Spring 2015
CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more
More informationProgramming 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 informationLearning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014
Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads
More information연세대학교전기전자공학과프로세서연구실박사과정김재억.
이강좌는연세대학교이용석교수연구실에서제작되었으며 copyright가없으므로비영리적인목적에한하여누구든지복사, 배포가가능합니다. 연구실홈페이지에는 고성능마이크로프로세서에관련된많은강의가있으며누구나무료로다운로드받을 수있습니다. 연세대학교전기전자공학과프로세서연구실박사과정김재억 Email: yonglee@yonsei.ac.kr 멀티스레드프로그래밍 (Multithreaded
More informationCOMP31212: Concurrency A Review of Java Concurrency. Giles Reger
COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other
More informationEE458 - Embedded Systems Lecture 8 Semaphores
EE458 - Embedded Systems Lecture 8 Semaphores Outline Introduction to Semaphores Binary and Counting Semaphores Mutexes Typical Applications RTEMS Semaphores References RTC: Chapter 6 CUG: Chapter 9 1
More informationDesign Patterns. SE3A04 Tutorial. Jason Jaskolka
SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November 18/19, 2014 Jason Jaskolka 1 / 35 1
More informationOnly one thread can own a specific monitor
Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification
More informationCS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03
CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption
More informationSoftware Design COSC 4353/6353 D R. R A J S I N G H
Software Design COSC 4353/6353 D R. R A J S I N G H Creational Design Patterns What are creational design patterns? Types Examples Structure Effects Creational Patterns Design patterns that deal with object
More informationTHOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS
THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS LOGISTICS HW3 due today HW4 due in two weeks 2 IN CLASS EXERCISE What's a software design problem you've solved from an idea you learned from someone else?
More informationINF 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 informationConcurrency, Thread. Dongkun Shin, SKKU
Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point
More informationThreads. 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 informationCIS192 Python Programming
CIS192 Python Programming Profiling and Parallel Computing Harry Smith University of Pennsylvania November 29, 2017 Harry Smith (University of Pennsylvania) CIS 192 November 29, 2017 1 / 19 Outline 1 Performance
More informationCS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017
CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution
More informationCS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables
CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 8: Semaphores, Monitors, & Condition Variables 8.0 Main Points: Definition of semaphores Example of use
More informationA few important patterns and their connections
A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Plan Singleton Factory method Facade and how they are connected. You should understand how to
More informationPlan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade
Plan A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Singleton Factory method Facade and how they are connected. You should understand how to
More informationReal-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify
http://cs.lth.se/eda040 Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify Klas Nilsson 2016-09-20 http://cs.lth.se/eda040 F4: Monitors: synchronized, wait and
More informationCMSC 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 informationCSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019
CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion Ruth Anderson Winter 2019 Toward sharing resources (memory) So far, we have been studying parallel algorithms
More informationJava Threads and intrinsic locks
Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object
More informationCS 160: Interactive Programming
CS 160: Interactive Programming Professor John Canny 3/8/2006 1 Outline Callbacks and Delegates Multi-threaded programming Model-view controller 3/8/2006 2 Callbacks Your code Myclass data method1 method2
More informationDesign Patterns. Dr. Rania Khairy. Software Engineering and Development Tool
Design Patterns What are Design Patterns? What are Design Patterns? Why Patterns? Canonical Cataloging Other Design Patterns Books: Freeman, Eric and Elisabeth Freeman with Kathy Sierra and Bert Bates.
More informationSynchronization COMPSCI 386
Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose
More informationChair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization
More informationCMSC 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 informationDESIGN PATTERN - INTERVIEW QUESTIONS
DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions
More informationSingleton. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 29
Singleton Computer Science and Engineering College of Engineering The Ohio State University Lecture 29 Preventing Instantiation Default (zero-argument) constructor Provided only if there is no explicit
More informationCS 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 informationObject Oriented Methods with UML. Introduction to Design Patterns- Lecture 8
Object Oriented Methods with UML Introduction to Design Patterns- Lecture 8 Topics(03/05/16) Design Patterns Design Pattern In software engineering, a design pattern is a general repeatable solution to
More informationWhat's wrong with Semaphores?
Next: Monitors and Condition Variables What is wrong with semaphores? Monitors What are they? How do we implement monitors? Two types of monitors: Mesa and Hoare Compare semaphore and monitors Lecture
More informationConcurrent Programming Lecture 10
Concurrent Programming Lecture 10 25th September 2003 Monitors & P/V Notion of a process being not runnable : implicit in much of what we have said about P/V and monitors is the notion that a process may
More informationConcurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads
Concurrency - Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads 1 Introduction Concurrency can occur at four levels: Machine instruction
More informationCPS221 Lecture: Threads
Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process
More informationConcurrency: State Models & Design Patterns
Concurrency: State Models & Design Patterns Practical Session Week 02 1 / 13 Exercises 01 Discussion Exercise 01 - Task 1 a) Do recent central processing units (CPUs) of desktop PCs support concurrency?
More informationPerformance 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 informationCS455: 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 informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationRobotics and Autonomous Systems
1 / 38 Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 2 / 38 Today Some more programming techniques that
More informationCSC369 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 informationJava 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 informationSummary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data
Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation
More informationProgrammazione di sistemi multicore
Programmazione di sistemi multicore A.A. 2015-2016 LECTURE 12 IRENE FINOCCHI http://wwwusers.di.uniroma1.it/~finocchi/ Shared-memory concurrency & mutual exclusion TASK PARALLELISM AND OVERLAPPING MEMORY
More informationWorking With Ruby Threads. Copyright (C) 2013 Jesse Storimer. This book is dedicated to Sara, Inara, and Ora, who make it all worthwhile.
Working With Ruby Threads Copyright (C) 2013 Jesse Storimer. This book is dedicated to Sara, Inara, and Ora, who make it all worthwhile. Chapter 16 Puma's Thread Pool Implementation Puma 1 is a concurrent
More informationCS342: Software Design. November 21, 2017
CS342: Software Design November 21, 2017 Runnable interface: create threading object Thread is a flow of control within a program Thread vs. process All execution in Java is associated with a Thread object.
More informationThreads 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 informationJava 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 informationUNIT V CONCURRENT PROGRAMMING
UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such
More informationMore on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson
More on Design CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson Outline Additional Design-Related Topics Design Patterns Singleton Strategy Model View Controller Design by
More informationCS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11
CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table
More informationSystèmes d Exploitation Avancés
Systèmes d Exploitation Avancés Instructor: Pablo Oliveira ISTY Instructor: Pablo Oliveira (ISTY) Systèmes d Exploitation Avancés 1 / 32 Review : Thread package API tid thread create (void (*fn) (void
More informationContribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team
http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples
More informationECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017
ECE 550D Fundamentals of Computer Systems and Engineering Fall 2017 The Operating System (OS) Prof. John Board Duke University Slides are derived from work by Profs. Tyler Bletsch and Andrew Hilton (Duke)
More informationCPSC 310 Software Engineering. Lecture 11. Design Patterns
CPSC 310 Software Engineering Lecture 11 Design Patterns Learning Goals Understand what are design patterns, their benefits and their drawbacks For at least the following design patterns: Singleton, Observer,
More informationRecap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack
What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for? Lightweight programming construct for concurrent activities How to implement? Kernel thread vs.
More informationChap. 6 Part 1. CIS*3090 Fall Fall 2016 CIS*3090 Parallel Programming 1
Chap. 6 Part 1 CIS*3090 Fall 2016 Fall 2016 CIS*3090 Parallel Programming 1 Chap 6: specific programming techniques Languages and libraries Authors blur the distinction Languages: access parallel programming
More informationConcurrent 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 informationNeed for synchronization: If threads comprise parts of our software systems, then they must communicate.
Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.
More informationWhat is a thread anyway?
Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently
More informationToro Documentation. Release A. Jesse Jiryu Davis
Toro Documentation Release 1.0.1 A. Jesse Jiryu Davis January 27, 2016 Contents i ii Toro logo by Musho Rodney Alan Greenblat With Tornado s gen module, you can turn Python generators into full-featured
More informationTuesday, October 4. Announcements
Tuesday, October 4 Announcements www.singularsource.net Donate to my short story contest UCI Delta Sigma Pi Accepts business and ICS students See Facebook page for details Slide 2 1 Design Patterns Design
More informationParallel Programming Languages COMP360
Parallel Programming Languages COMP360 The way the processor industry is going, is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight,
More information04-Java Multithreading
04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org
More informationCSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010
CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion Tyler Robison Summer 2010 1 Toward sharing resources (memory) So far we ve looked at parallel algorithms using fork-join
More informationResource management. Real-Time Systems. Resource management. Resource management
Real-Time Systems Specification Implementation Verification Mutual exclusion is a general problem that exists at several levels in a real-time system. Shared resources internal to the the run-time system:
More informationExperience with Processes and Monitors in Mesa. Arvind Krishnamurthy
Experience with Processes and Monitors in Mesa Arvind Krishnamurthy Background Focus of this paper: light-weight processes (threads) and how they synchronize with each other History: Second system; followed
More informationThe Singleton Pattern. Design Patterns In Java Bob Tarr
The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,
More informationCSE 451 Midterm 1. Name:
CSE 451 Midterm 1 Name: 1. [2 points] Imagine that a new CPU were built that contained multiple, complete sets of registers each set contains a PC plus all the other registers available to user programs.
More informationCMSC 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 informationThreads 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 informationVirtual Machine Design
Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview
More informationReal-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology
Real-Time Systems Lecture #4 Professor Jan Jonsson Department of Computer Science and Engineering Chalmers University of Technology Real-Time Systems Specification Resource management Mutual exclusion
More informationObject Oriented Design
Singleton Pattern Singleton Pattern Intent - Ensure that only one instance of a class is created. - Provide a global point of access to the object. Implementation The implementation involves a static member
More informationCondition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois
Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:
More informationTHREADS AND MULTITASKING ROBOTS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 comp329-2013-parsons-lect10 2/37 Today Some more programming techniques that will be helpful
More informationROBOTICS AND AUTONOMOUS SYSTEMS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 THREADS AND MULTITASKING ROBOTS comp329-2013-parsons-lect10 2/37 Today Some more programming
More informationTwisted is the first library we ll be working with that does not come with the Python Standard Library.
LECTURE 12 Twisted TWISTED Last lecture, we introduced the mental model needed to work with Twisted. The most important points to keep in mind are: Twisted is asynchronous. Multiple independent tasks may
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),
More informationLast Class: Synchronization
Last Class: Synchronization Synchronization primitives are required to ensure that only one thread executes in a critical section at a time. Concurrent programs Low-level atomic operations (hardware) load/store
More informationcs Java: lecture #6
cs3101-003 Java: lecture #6 news: homework #5 due today little quiz today it s the last class! please return any textbooks you borrowed from me today s topics: interfaces recursion data structures threads
More informationCS 351 Design of Large Programs Singleton Pattern
CS 351 Design of Large Programs Singleton Pattern Brooke Chenoweth University of New Mexico Spring 2019 The Notion of a Singleton There are many objects we only need one of: Thread pools, caches, dialog
More informationTHREADS AND CONCURRENCY
THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on
More informationMultithreaded Programming
Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes
More informationAC59/AT59/AC110/AT110 OPERATING SYSTEMS & SYSTEMS SOFTWARE DEC 2015
Q.2 a. Explain the following systems: (9) i. Batch processing systems ii. Time sharing systems iii. Real-time operating systems b. Draw the process state diagram. (3) c. What resources are used when a
More informationCSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich
CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and
More informationbe used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate
UNIT 4 GRASP GRASP: Designing objects with responsibilities Creator Information expert Low Coupling Controller High Cohesion Designing for visibility - Applying GoF design patterns adapter, singleton,
More information