1

I have multiple methods set up that need to be run simultaneously. I decided to create individual threads for said methods. There is also a method I made with the sole purpose of creating another thread. Here is an example of what I have done. My question is, how can I safely close these threads?

from threading import Thread

....

def startOtherThread():
    Thread(target = myMethod).start()

Thread(target = anotherMethod).start()

....
PL43
  • 13
  • 2
  • See the following question for more info: http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – Mark Hildreth Aug 14 '12 at 23:23

1 Answers1

2

You do not close threads. They will run until your target= method is finished. It is not clear why you are trying to introduce separate method to start a thread: Thread(target=...).start() looks simple enough.

When you work with threads, you have three basic options:
- wait in main thread until child thread is finished using join() function
- just let child thread run by doing nothing
- exit child thread when main thread is over by using setDeamon(True) on the thread object.

Also you need to be aware of GIL (Global Interpreter Lock) in cPython

Here is some basic test code for threads:

import threading
import time
import sys


def f():
    sys.stderr.write("Enter\n")
    time.sleep(2)
    sys.stderr.write("Leave\n")


if __name__ == '__main__':
    t0 = threading.Thread(target=f)
    t1 = threading.Thread(target=f)
    t0.start()
    time.sleep(1)
    t1.setDaemon(True)
    t1.start()
    #t1.join()
Yevgen Yampolskiy
  • 7,022
  • 3
  • 26
  • 23