Click here to load reader
Upload
learnbayin
View
178
Download
3
Embed Size (px)
Citation preview
MultiThreading in PythonMultithreading
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
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.
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
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
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
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.