Python supports multiple threads through the thread module, and the syntax is concise. Now let's look at the multithreading in Python through an example:
Import threadimport time # ensure that only one additional thread is started isrunning = false # Start time control. The test time is, so it depends on this time, it can be used to specify the execution time of scheduled tasks. timer_hour = 23timer_min = 44 # Another thread processes the task def another_thread (): print '[another_thread] is start... '# declare to use the global variable isrunning global isrunning # For loop simulation task execution for I in range (3): time. sleep (1) print '[another_thread] Time: % s' % time. strftime ('% Y-% m-% d % x', time. localtime () print '[another_thread] is running: % s' % isrunning # This is only to ensure that the task is started only once a day and the time of one minute does not exceed 60 seconds. sleep (60) print '[another_thread] is end... '# this status is only used to ensure that the task will not be started repeatedly. Of course, you can set a time-out period for the task, when the time does not end, the isrunning is automatically terminated. = falseif _ name _ = '_ main _': While true: Now = time. localtime () print '[main_thread] Time: % s' % time. strftime ('% Y-% m-% d % x', now) print' [main_thread] is running: % s' % isrunning if now. tm_hour = timer_hour and now. tm_min = timer_min and not isrunning: # Set to true before entering the task to prevent repeated start of isrunning = true # Start a new thread in Python, you can see from the following information about the log printing, and it does not affect the running thread of the main thread. start_new_thread (another_thread, () time. sleep (1)
After the code is executed:
C:\Users\Captain\Desktop>python task.py[main_thread] time: 2013-07-31 23:44:56[main_thread] Is Running: False[another_thread] is start...[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59[another_thread] Is Running: True[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:00[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:01[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:02
This instance is simple. It can be applied to scheduled tasks, heartbeat detection, daemon processes, and other actual scenarios.