Python Forum
How does a python thread work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does a python thread work?
#1
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.
Reply


Messages In This Thread
How does a python thread work? - by jackbk - May-31-2017, 07:02 AM
RE: How does a python thread work? - by wavic - May-31-2017, 07:06 AM
RE: How does a python thread work? - by jackbk - May-31-2017, 07:23 AM
RE: How does a python thread work? - by Larz60+ - May-31-2017, 10:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Process doesn't work but Thread work ! mr_byte31 4 2,754 Oct-18-2021, 06:29 PM
Last Post: mr_byte31
  Is there a way to not terminate a running thread in python Contra_Boy 3 2,067 May-05-2020, 09:38 PM
Last Post: SheeppOSU
  Error SQLite objects created in a thread can only be used in that same thread. binhduonggttn 3 15,833 Jan-31-2020, 11:08 AM
Last Post: DeaD_EyE
  Python Thread stops execution neethuvp 1 3,478 Feb-18-2019, 06:36 PM
Last Post: micseydel
  Debugging inside a thread with Python 2.3.4 zerajera 0 1,745 Nov-21-2018, 01:43 PM
Last Post: zerajera

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020