7

Click here to load reader

Python Training in Bangalore | Multi threading | Learnbay.in

Embed Size (px)

Citation preview

Page 1: Python Training in Bangalore | Multi threading | Learnbay.in

MultiThreading in PythonMultithreading

Page 2: Python Training in Bangalore | Multi threading | Learnbay.in

What are threads?

Thread is smallest unit that can be scheduled in an operating system.

Process vs Thread?

Multiple threads within a process share the same data space with the main thread

Threads sometimes called light-weight processes and they do not require much memory overhead

Create a Process:

Code: https://repl.it/IIpm/0

Page 3: Python Training in Bangalore | Multi threading | Learnbay.in

Threading in Python

There are two modules which support the usage of threads in Python:

Thread

Threading (We should use threading model instead of thread)

The module "thread" treats a thread as a function, while "threading module " is implemented in OOPS

way, i.e. every thread corresponds to an object.

Page 4: Python Training in Bangalore | Multi threading | Learnbay.in

Thread Module

we can use the function thread.start_new_thread:

thread.start_new_thread(function, args)

Method starts a new thread and return its identifier.Thread starts

and execute the handler function “function” with args as argument.

“Args” should be a tuple.

Code Example: https://repl.it/IIqg/3

Page 5: Python Training in Bangalore | Multi threading | Learnbay.in

Thread Lock

Discuss about atomic operation.What happens to global variable in case of

multithreading.

Problem in this code: https://repl.it/IIz1/0

Use lock_object = thread.allocate_lock()

And lock.acquire() and lock.release()

Code example: https://repl.it/IIyL/2

Page 6: Python Training in Bangalore | Multi threading | Learnbay.in

Threading Module

Threading module builds on the low-level features of thread to make working

with threads even easier and threads are implemented as objects.

Basic Example: https://repl.it/IJAB/3

Page 7: Python Training in Bangalore | Multi threading | Learnbay.in

Create a thread - Threading Module

Follow below steps:

Construct a subclass from the <Thread> class.

Override the <__init__(self [,args])> method to provide arguments.

override the <run(self [,args])> method to code the actual required logic of the thread.

When start is called on instance of Thread subclass,it eventually calls overridden run method.