The above section of code, for example, how to see the number of threads running, you need to call the enumerate method inside the threading module, return a list of thread numbers:
ImportThreadingImport Time"""the code for the above chapter is an example of how to see how many threads are running"""defSing ():"""sing for 5 seconds""" forIinchRange (3): Print('----------------') Print('I'm singing ....') Time.sleep (1)defDance (): forIinchRange (5): Print('I was dancing ....') Print('----------------') Time.sleep (1)defMain (): T= Threading. Thread (target=sing) T2= Threading. Thread (target=dance) T.start () T2.start ()#cycles through the number of running threads, calling the enumerate method in the threading module to return a list of elements that are running threads, and the number of elements that are printed whiletrue:nums=Len (threading.enumerate ())Print(Threading.enumerate ())#when there are no threads, exit ifNums <= 1: BreakTime.sleep (1)if __name__=='__main__': Main ()
The results of the operation are as follows:
I'm singing ....
I was dancing ....
[<_mainthread (Mainthread, started 26264), <thread (Thread-1, started 23804);, <thread (Thread-2, Started 24216);]
[<_mainthread (Mainthread, started 26264), <thread (Thread-1, started 23804);, <thread (Thread-2, Started 24216);]
I was dancing ....
I'm singing ....
[<_mainthread (Mainthread, started 26264), <thread (Thread-1, started 23804);, <thread (Thread-2, Started 24216);]
I'm singing ....
I was dancing ....
[<_mainthread (Mainthread, started 26264), <thread (Thread-1, started 23804);, <thread (Thread-2, Started 24216);]
I was dancing ....
[<_mainthread (Mainthread, started 26264), <thread (Thread-2, started 24216);]
I was dancing ....
[<_mainthread (Mainthread, started 26264), <thread (Thread-2, started 24216);]
[<_mainthread (Mainthread, started 26264);]
Explanations such as:
Network Programming-thread-2, how to see how many threads are running