Python Multithreaded Programming
When programmers run a simple program of Python, execution starts at the first line and proceeds line-by-line. Also, functions & loops may be the reason of program execution to jump but it is fairly easy to see its working procedures and which line will be next executed. Programmers can put their fingers and can trace the lines of codes that will be executed; this is called single threaded programming.However, in case of multi-threaded programming, it’s like putting a second finger on your program. Both the fingers move the same way and will be executed simultaneously.
What Are Threads?
It is the execution of tiny sequence of program instruction that can be managed independently and is a distinctive part of operating system. Modern OS manage multiple programs using time-sharing technique. In Python, there are two different kinds of thread. These are:
Why To Use Thread
Thread plays a major role in application programming. All the GUI programs and web servers are threaded together. The main reasons of using threads are:
Thread Modules In Python
There are two ways for accessing Python threads. These are by using:
It is to be noted that ‘tread’ module has been considered as of lesser use and hence users get to use the ‘threading’ module instead. Another thing has to keep in mind that the module ‘thread’ treats the thread like a function whereas the ‘threading’ is implemented as an object.
Benefits Of Threading
In a thread, there are three different parts. It has the beginning, an execution part and a conclusion. It also has an instruction pointer that points to where the thread or process is currently running and hence the thread is able to run several different program blocks concurrently.
Using A New Thread
It is achievable to execute functions in a separate thread using a module Thread. For doing this, programmers can use the function – thread.start_new_thread().
Syntax:
thread.start_new_thread(function, args[, kwargs])
Here, the first part is a method as told before & this method is a faster and more efficient way to create new threads. As the child thread starts the function passes list of args. The thread gets terminated when the function returns a value. The ‘args’ in the above syntax is a tuple of arguments.
Program Of Threading Using Python
Example:
#!/usr/bin/python
import threading
def coder(number):
print ' Coders: %s' , %number
return
threads = []
for k in range(5):
t = threading.Thread(target=coder, args=(k,))
threads.append(t)
t.start()
Output:
Coders: 0
Coders: 1
Coders: 2
Coders: 3
Coders: 4
Methods Of Thread Class
The threading module, as described earlier has a Thread class that is used for implementing threads and that class also contains some predefined methods used by programmers in multi-threaded programming. These are:
Comments
Post a Comment