Getting started with thread basic instance for python development, pythonthread
This article describes 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: [<Thread (Thread-2, started 3480)>, <Thread (Thread-1, started 660)>, <Thread (SockThread, started daemon 2920)>, <Thread (Thread-3, started 916)>, <Thread (Thread-4, started 3476)>, <_ MainThread (MainThread, started 3964)>, <Thread (Thread-5, started 2060)>] 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:
>>> [<Thread (SockThread, started daemon 15424)>, <Thread (Thread-3, started 15840)>, <Thread (Thread-1, started 10884)>, <Thread (Thread-2, started 14512)>, <Thread (Thread-4, started 13204)>, <_ MainThread (MainThread, started 12924)>, <Thread (Thread-5, started 15476)>] Number of existing threads: 7 >>> Good! Good! Good! Good! Good!
I hope this article will help you with Python programming.