Wednesday, February 3, 2016

Multi-threading in Python

How to create multi-threaded programs in Python?

Before going into programming we will give you small introductions about threads. A thread is a light weight component of a process in operating system which can act just like a process and it can share its resources i.e. memory with another threads. The operating system should have thread schedular in order to make sure which thread will get the CPU at time t.

Threads are very useful for parallel execution of programs.

In the below example we will create some threads and show you how we can execute multiple threads simultaneously.

=====
import threading
import time
class X:
   def myfunction(self,firstName,age=20):
      print threading.currentThread().getName(), 'start'
      time.sleep(3)
      print firstName,age
      print threading.currentThread().getName(), 'end of myfunction method'
threads=[]
x=X()
for i in range(4):
    t = threading.Thread(target=x.myfunction, args=(i,),kwargs={'age':21})
    threads.append(t)
[x.start() for x in threads]
=====
Here we have created 4 threads and all threads are executing myfunction inside class X.

We have passed method arguments as args which is a tuple.
We have passed method optional arguments as kwargs which is a dict. The key of the dict will be the variable name in the method.

Here in the above example, args=(1,) means  firstName=1
and kwargs={'age':21} means we passed age=21 not 20 as default. 

Ouput:
------------------------------------------------
Thread-1 start
Thread-2 start
Thread-3 start
Thread-4 start

0 21
Thread-1 end of myfunction method
1 21
Thread-2 end of myfunction method
2 21
Thread-3 end of myfunction method
3 21
Thread-4 end of myfunction method
---------------------------------------------------

Try it yourself and comment in case you have any questions.

No comments:

Post a Comment