Turn: python multithreading is so simple, python Multithreading
Multithreading
Technology is developing, the times are improving, and our CPU is getting faster and faster. CPU complaints. P takes some time for me. In fact, it's okay for me to do multiple jobs at the same time; as a result, the operating system has entered the multi-task era. It's not our dream to listen to music and eat hot pot.
Python provides two modules to implement multi-threaded thread and threading. thread has some shortcomings and can be compensated in threading. In order not to waste you and time, we can simply learn threading.
Continue to transform the above example and introduce threadring to play music and video simultaneously:
# Coding = utf-8import threadingfrom time import ctime, sleepdef music (func): for I in range (2): print "I was listening to % s. % s "% (func, ctime () sleep (1) def move (func): for I in range (2): print" I was at the % s! % S "% (func, ctime () sleep (5) threads = [] t1 = threading. thread (target = music, args = (u 'Sale of love',) threads. append (t1) t2 = threading. thread (target = move, args = (u 'avant',) threads. append (t2) if _ name _ = '_ main _': for t in threads: t. setDaemon (True) t. start () print "all over % s" % ctime ()
Import threading
First, import the threading module, which is the prerequisite for multithreading.
Threads = []
T1 = threading. Thread (target = music, args = (u 'Sale of love ',))
Threads. append (t1)
The threads array is created, Thread t1 is created, and the threading. Thread () method is used. In this method, the music method target = music is called, and The args method is used to transmit parameters to music. Install the created thread t1 in the threads array.
Then, create thread t2 in the same way and load the t2 to the threads array.
For t in threads:
T. setDaemon (True)
T. start ()
Finally, the array is traversed through the for loop. (The array is loaded with t1 and t2 threads)
SetDaemon ()
SetDaemon (True) declares a thread as a daemon. It must be set before the start () method is called. If it is not set as a daemon, the program will be suspended infinitely. After the sub-thread starts, the parent thread continues to execute. After the parent thread finishes executing the last statement print "all over % s" % ctime (), it does not wait for the sub-thread, the sub-thread is also terminated.
Start ()
Start thread activity.
Running result:
>>>============================== RESTART ============== ==================================>>> I was listening to love trading. thu Apr 17 12:51:45 2014 I was at the Avatar! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014
According to the execution results, both the Sub-thread (muisc, move) and the main thread (print "all over % s" % ctime () start at the same time, however, since the execution of the main thread ends, the sub-thread is terminated.
Continue the adjustment procedure:
...if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print "all over %s" %ctime()
We only add a join () method to the above program to wait for the thread to terminate. The function of join () is that the parent thread of this subthread will be blocked until the subthread completes running.
Note: The position of the join () method is outside the for loop. That is to say, the main process must be executed only after the two processes in the for loop are completed.
Running result:
I was listening to love trading. Thu Apr 17 13:04:11 2014 I was at the Avatar! Thu Apr 17 13:04:11 2014I was listening to love trading. Thu Apr 17 13:04:12 2014I was at the Avatar! Thu Apr 17 13:04:16 2014all over Thu Apr 17 13:04:21 2014
From the execution results, we can see that music and move are started at the same time.
The start time is 4 minutes 11 seconds until the main process called is 4 minutes 21 seconds and the total time is 10 seconds. It is reduced from a single thread by 2 seconds. We can adjust the sleep () Time of music to 4 seconds.
...def music(func): for i in range(2): print "I was listening to %s. %s" %(func,ctime()) sleep(4)...
The sub-thread starts for 11 minutes and 27 seconds, and the main thread runs for 11 minutes and 37 seconds.
Although each song of music has been extended from 1 second to 4, the total time for running the script through multiple threads remains unchanged.