This article mainly introduces the thread basics of python development, and analyzes the basic usage of thread threads in Python in the form of three instances, it involves the execution principle and thread operation skills of serial and parallel programs. If you need it, refer to the example in this article to describe the thread basics of python development. We will share this with you for your reference. The details are as follows:
Speaking of threads, we need to know what serial programs are and what parallel programs are.
For example:
A serial Program is an execution program.
# Python threadingimport time''' output every second: this is a demo! '''Def serial (): ''' serial Output ''' time. sleep (1) print ('this is a demo! ') Def main (): for I in range (5): serial () if _ name _ =' _ main _ ': main ()
The running result is as follows:
>>> this is a demo!this is a demo!this is a demo!this is a demo!this is a demo!>>>
Parallel Programs are executed by many programs at the same time (macro ).
# Python threadingimport time ''' for parallel execution. Output: Good! Good! Good! Good! Good! '''Def parallel (): ''' and output ''' time. sleep (1) print ('Good! ') Def main (): for I in range (5): t = threading. thread (target = parallel) t. start () if _ name _ = '_ main _': main ()
Of course, by executing programs, we can know that parallel programs are faster than serial programs ....
We can also get the current thread and number:
# Python threadingimport time ''' for parallel execution. Output :[
,
,
,
,
, <_ MainThread (MainThread, started3964)>,
] Number of threads: 7 Good! Good! Good! Good! Good! '''Def parallel (): ''' and output ''' time. sleep (1) print ('Good! ') Def main (): for I in range (5): t = threading. thread (target = parallel) t. start () if _ name _ = '_ main _': main () print (threading. enumerate () print ('Number of threads: % d' % threading. active_count ())
The running result is as follows:
>>> [
,
,
,
,
, <_ MainThread (MainThread, started12924)>,
] Number of threads: 7 >>> Good! Good! Good! Good! Good!
I hope this article will help you with Python programming.