Tuesday, January 14, 2014

Advanced : Thread , Threading & Queues

Threads in python is nothing just a running multiple tasks, functions calls at the same time so let's understand how we can run multiple functions or tasks in python. First we learn how to create a thread & then we use the thread means define job to the threads

so here we using thread & threading class to do that all job let's see how to create a thread
we can create a new thread by just
thread.start_new_thread ( function, arg[]) 

a simple code snippet to create a thread so that we can work with it here is the code if i explain you about code then just understand we can divide this code in 2 parts First we are going to create a  new thread in for while loop with the name new_thread 

next we need to define a function in the upper part of a program with the same name as our thread name & pass the arg inside it as id 



now run the script & we can see the thread created & it will continue executing in for while loop


So this is a very cool program about how to create a thread using thread module in python. Next we are going to understand about threading a multithreading in python

Now we are going to study about threading & Queue method
if i explain you something about this code then see we are defining a subclass of the Thread class & override the __init__, and run method.
here we are importing three modules
threading
Queue
time
why these all & what combinations they made with threading actually there is lock which restrict the multi threading in on shell so we are here executing multiple threads in a Queue one by by one after a certain time interval   :p let's perform this task in windows python shell  :')



Let's see how this code is working, how multiple threads are working in a queue or not working ....


voila it's working fine here we can see multiple threads are running after an interval of time see in output First we created the threads then ordered to sleep & finally finish the sleeping    \ :) /  \ ^_^ /



No comments:

Post a Comment