Just started to learn multi-threading when a joke in the use of Python thread printing things found that their own thread data is not printed, looking for a long time did not find the problem, nor the nerve to ask, oneself suppress a long time only to find the problem!
The code is as follows:
import threadingdef SayHi(): print(‘say hi !‘)def SeyHello(): print(‘say hello !‘)print(‘start‘)threading._start_new_thread(SayHi,())threading._start_new_thread(SeyHello,())print(‘end‘)
The result of this output is that there is no output of the function,
Have not found the reason, and then on the Internet to find examples, follow the online example to do all right, but I wrote on the problem, and then found that the online example of multi-threading, multi-process are imported time module, I have time not to add to the script of the others are the same, and then try to join the time module to do, The results show that there is still no output.
The code is as follows:
import threadingfrom time import sleepdef SayHi(): sleep(2) print(‘say hi !‘)def SeyHello(): sleep(2) print(‘say hello !‘)print(‘start‘)threading._start_new_thread(SayHi,())threading._start_new_thread(SeyHello,())print(‘end‘)
But at one time inadvertently found this can also be in the function of the value of the output, and then think is not enough time? And then the last side of the time to join finally came out.
import threadingfrom time import sleepdef SayHi(): sleep(2) print(‘say hi !‘)def SeyHello(): sleep(2) print(‘say hello !‘)print(‘start‘)threading._start_new_thread(SayHi,())threading._start_new_thread(SeyHello,())print(‘end‘)sleep(5)
Summarize:
Because of the threads that are turned on, their end times may be greater than the time of the main process, so the main process will not be able to output the main process if it is dead before they end, so the thread ends and the main process ends to see the output.
Meng New Python multithreading