Already In previous post you will have read about thread (how
to use thread in Pygtk (python)) . So theoretically
thread is nothing but a task which works independently.
A single computer running several programs (seemingly)
simultaneously. This is done by clever and frequent switching between the
execution states of each program. For example, the print spooler on your PC may
be printing pages from one document while you are editing another document in
your word processor.
Above was theoretical knowledge now we will see practically
programming means how to use simple thread and how to use multiple threading using
python.
Some Important point
about multithreading for your knowledge
- Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
- Threads sometimes called light-weight processes and they do not require much memory overhead; they care cheaper than processes.
- It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
- No one can stop threading once it started until completed. Only you can hold that thread as a sleeping, waiting or busy in some task.
#!/usr/bin/python import thread import time # Define a function for the thread def check_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread(check_time, ("Thread-1", 2, ) ) thread.start_new_thread(check_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread"When the above code is executed, it produces the following result:
Thread-1: Thu Jan 22 15:42:17 2009 Thread-1: Thu Jan 22 15:42:19 2009 Thread-2: Thu Jan 22 15:42:19 2009 Thread-1: Thu Jan 22 15:42:21 2009 Thread-2: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:25 2009 Thread-2: Thu Jan 22 15:42:27 2009 Thread-2: Thu Jan 22 15:42:31 2009 Thread-2: Thu Jan 22 15:42:35 2009Thanks Guys
No comments:
Post a Comment