![]() |
How does a python thread work? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How does a python thread work? (/thread-3527.html) |
How does a python thread work? - jackbk - May-31-2017 I have used Python thread so far, but I had a question that I can not find an answer by myself. Google some related information, but I do not satisfy with this. Do you have any experience with this? I have a thread as below (file name test_thread.py) import time def AThread(aEvent): while True: aEvent.wait() aEvent.clear() print "aEvent set already" aEvent = threading.Event() AThread = threading.Thread(name='AThread', target=AThread, args=(aEvent,)) try: AThread.start() except: print "Can not start AThread" time.sleep(5) aEvent.set()I have a thread named "AThread". This thread must wait for "aEvent" until "aEvent" is set. When I run this thread on Linux by invoking python test_thread.py, after 5 seconds, message "aEvent set already" is printed. After that, there is nothing because aEvent is set once in my program. It is normal. However, I want to know the below. 1. If I stop the test_thread.py by pressing Ctrl+C or Ctrl+Z, is the AThread really killed? I am not confident to say AThread is killed because test_thread.py still occur when I use "top" command on Linux terminal. 2. Is there any way to "stop" the thread? Where should we put a "stop" method to stop the thread in test_thread.py? Because I see we call "start()" method to start the thread, but there is no method to "stop" the thread. I see there is "join()" method can terminate a thread but I do not understand how to use it. RE: How does a python thread work? - wavic - May-31-2017 ^C will kill all the program. ^Z will send it as a background job. Linux? I can't answer the second question because I never used threads before. RE: How does a python thread work? - jackbk - May-31-2017 (May-31-2017, 07:06 AM)wavic Wrote: ^C will kill all the program. Thanks. I am using Linux. By the way, I met the following. Ctrl+C: Can not return to the prompt of terminal. It just show "KeyboardInterrupt", then I can not type any command. Ctrl+Z: Can return to the prompt. But test_thread.py still occurs by "top" command on Linux. So, I think my case is: I can return to prompt by pressing Ctrl+Z. But it makes the test_thread.py run as background. Do you know how to stop my test_thread.py? I used Ctrl+C but it can not return to the prompt, so I think test_thread.py can not be stopped! RE: How does a python thread work? - Larz60+ - May-31-2017 You need to set up communications between threads. ^C and ^Z are not options for a properly running system. I suggest you sit down for an hour and watch this video: https://www.youtube.com/watch?v=MCs5OvhV9S4 |