Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin.

Slides:



Advertisements
Similar presentations
Processes and Threads Chapter 3 and 4 Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee Community College,
Advertisements

Chapter 3 Process Description and Control
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Day 10 Threads. Threads and Processes  Process is seen as two entities Unit of resource allocation (process or task) Unit of dispatch or scheduling (thread.
Multithreaded Programming in Python Nick Anastasia.
1 Processes and Pipes COS 217 Professor Jennifer Rexford.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
1 Processes and Pipes. 2 "He was below me. I saw his markings, manoeuvred myself behind him and shot him down. If I had known it was Saint-Exupery, I.
Concurrency…leading up to writing a web crawler. Web crawlers.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Fundamentals of Python: From First Programs Through Data Structures
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
1 Chapter Client-Server Interaction. 2 Functionality  Transport layer and layers below  Basic communication  Reliability  Application layer.
 socket.socket() returns socket object: _socketobject  Most of socket API are methods on socket objects or functions  Value result arguments (e.g.,
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
1 Web Based Programming Section 8 James King 12 August 2003.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
Multiprogramming. Readings r Silberschatz, Galvin, Gagne, “Operating System Concepts”, 8 th edition: Chapter 3.1, 3.2.
Networks and Client/Server Applications Handling Multiple Clients Concurrently.
Concurrent Programming and Threads Threads Blocking a User Interface.
CS333 Intro to Operating Systems Jonathan Walpole.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
Laboratory - 4.  Threading Concept  Threading in.NET  Multi-Threaded Socket  Example.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Sistem Operasi © Sekolah Tinggi Teknik Surabaya 1.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 4: Threads.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
MULTIPROCESSING MODULE OF PYTHON. CPYTHON  CPython is the default, most-widely used implementation of the Python programming language.  CPython - single-threaded.
Multiprogramming. Readings r Chapter 2.1 of the textbook.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Prepared by Oussama Jebbar
Threaded Programming in Python
Networks and Client/Server Applications
Java Multithreading.
Multithreaded Programming in Java
CS399 New Beginnings Jonathan Walpole.
Operating Systems (CS 340 D)
Realizing Concurrency using Posix Threads (pthreads)
Networks and Client/Server Applications
Java Based Techhnology
Multithreaded Programming
Threaded Programming in Python
Operating Systems (CS 340 D)
Jonathan Walpole Computer Science Portland State University
21 Threads.
PROCESSES & THREADS ADINA-CLAUDIA STOICA.
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Multithreading in java.
CS510 Operating System Foundations
Representation and Management of Data on the Internet
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads

Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin execute end However, threads are NOT programs – they run within a program All threads within a program Are sequential processes Run “at the same time” Perform different tasks

Threads Multiple threads within a process share the same data space with the main thread share information easily communicate with each other more easily than if they were separate processes. Threads are “light-weight processes” do not require much memory overhead; cheaper than processes. Threads run independently and concurrently

Concurrent execution on a multi- processor computer Processor 2 Processor 1 Thread 1 Thread 2

Concurrent execution on a single-processor computer Thread 1 Thread 2 Time slice

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

Threads in python python provides language-level support for threads There are two modules _thread a low level thread implementation threading a high-level thread interface Three ways to implement threads Create a Thread instance, passing in a function Create a Thread instance, passing in a class Subclass Thread and create subclass instance

Thread in python Threading provides a class Thread Thread class methods run() start() join() getName() setName() is_alive() isDaemon

Structure of program The simplest approach instantiate a Thread class with a target function call start() to let it begin working. import threading def worker(): """thread worker function""" print 'Worker' return threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() $ python threading_simple.py Worker Output:

Passing arguments import threading def worker(num): """thread worker function""" print 'Worker: %s' % num return threads = [] for i in range(5): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() $ python -u threading_simpleargs.py Worker: 0 Worker: 1 Worker: 2 Worker: 3 Worker: 4

Sleeping import threading import time def worker(num): """thread worker function""” time.sleep(1) print 'Worker: %s' % num return threads = [] for i in range(5): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() $ python -u threading_simpleargs.py Worker: 0 Worker: 1 Worker: 2 Worker: 3 Worker: 4

Example 3 (with classes ) import threading import time class MyThread(threading.Thread): def run(self): print("{} started!".format(self.getName())) # "Thread-x started!" time.sleep(1) # Pretend to work for a second print("{} finished!".format(self.getName())) # "Thread-x finished!" if __name__ == '__main__': for x in range(4): # Four times... mythread = MyThread(name = "Thread-{}".format(x + 1)) #...Instantiate a thread and pass a unique ID to it mythread.start() #...Start the thread time.sleep(.9) #...Wait 0.9 seconds before starting another

import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) print_time(self.name, self.counter, 5) print ("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 def main(): # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() print ("Exiting Main Thread”) main() Example 4 (classes)

Threads for socket communication In the networked program for calculating the area of a circle we want to modify the program so that any number of clients may connect to the server and request an area calculation “Round robin” approach not best Clients not communicating with each other Service is totally independent for each At any time, any number of clients may connect or disconnect

server Client 1 Client n … radius area

Example area_client.py area_server.py