Learn the Python multithreading today and want to show whether the current thread is the main or child thread. A search on the internet, there is a way to call
1 threading.current (). Name
Dinghai Accidental
However, it is found that the same threading.current_thread () is not only followed by the. Name property, but also the. GetName () method. But
The final result of these 2 formulations is the same.
So, what's the difference between the 2 people?
1 ImportThreading2 Import Time3 4 defRun (ARG):5 Print("Running Sub thread ... {}". Format (Threading.current_thread ()))6Time.sleep (3)7 8 if __name__=="__main__":9T1 = Threading. Thread (target=run,args= ("T1",))Ten T1.start () One Print("Mian Thread ... {}". Format (Threading.current_thread (). GetName ())) A Print("Mian Thread ... {}". Format (Threading.current_thread (). Name)) - -T2 = Threading. Thread ()
Dinghai Accidental
Name is a property of the current thread, and GetName is the method of the current thread.
Although the results of Threading.current_thread (). Name and Threading.current_thread (). GetName () are the same, they are not the same thing at all, for example, by threading.current _thread (). Name = ' Thread_python ' to change it.
Final Demo Code:
1 ImportThreading2 Import Time3 4 defRun (ARG):5 Print("Running Sub thread ... {}". Format (Threading.current_thread ()))6Threading.current_thread (). name="Xurui_python"7 Print("sub1 Thread ... {}". Format (Threading.current_thread (). GetName ()))8 Print("sub2 Thread ... {}". Format (Threading.current_thread (). Name))9Time.sleep (3)Ten One if __name__=="__main__": AT1 = Threading. Thread (target=run,args= ("T1",)) - T1.start () - Print("mian1 Thread ... {}". Format (Threading.current_thread (). GetName ())) the Print("mian2 Thread ... {}". Format (Threading.current_thread (). Name))
Demo Code
Code results:
1 running sub Thread...<thread (Thread-1, started 23296) >2mian1 thread ... Mainthread3mian2 Thread ... Mainthread4sub1 thread...xurui_python5 sub2 Thread...xurui_python
Code Results
What is the difference between Python threading.current_thread (). Name and. GetName ()