如何从另一个线程中杀死线程?
How to kill thread from inside another thread?
我有两个线程函数(使用线程)。一旦满足要求,我想由第二个线程杀死第一个线程,并允许第二个线程继续 运行。在代码中,它是这样的:
import threading
import time
def functA():
print("functA started")
while(1):
time.sleep(100)
def functB(thread1):
print("functB started")
thread1.start()
x=0
while(x<3):
x=x+1
time.sleep(1)
print(x)
print(threading.enumerate())
thread1.exit() #<---- kill thread1 while thread2 continues....
while(1):
#continue doing something....
pass
thread1 = threading.Thread(target=functA)
thread2 = threading.Thread(target=functB,args=(thread1,))
thread2.start()
如何从线程 2 中杀死线程 1 并继续保留线程 2 运行?
以下是使用关闭标志的方法:
thread_a_active = True
def functA():
print("functA started")
while thread_a_active:
time.sleep(1)
def functB(thread1):
print("functB started")
thread1.start()
x=0
while x<3:
x=x+1
time.sleep(1)
print(x)
print(threading.enumerate())
thread_a_active = False
while True:
#continue doing something....
pass
顺便说一句,Python 中的 while
和 if
语句不使用外括号。这是 C 程序员遗留下来的坏习惯。
我有两个线程函数(使用线程)。一旦满足要求,我想由第二个线程杀死第一个线程,并允许第二个线程继续 运行。在代码中,它是这样的:
import threading
import time
def functA():
print("functA started")
while(1):
time.sleep(100)
def functB(thread1):
print("functB started")
thread1.start()
x=0
while(x<3):
x=x+1
time.sleep(1)
print(x)
print(threading.enumerate())
thread1.exit() #<---- kill thread1 while thread2 continues....
while(1):
#continue doing something....
pass
thread1 = threading.Thread(target=functA)
thread2 = threading.Thread(target=functB,args=(thread1,))
thread2.start()
如何从线程 2 中杀死线程 1 并继续保留线程 2 运行?
以下是使用关闭标志的方法:
thread_a_active = True
def functA():
print("functA started")
while thread_a_active:
time.sleep(1)
def functB(thread1):
print("functB started")
thread1.start()
x=0
while x<3:
x=x+1
time.sleep(1)
print(x)
print(threading.enumerate())
thread_a_active = False
while True:
#continue doing something....
pass
顺便说一句,Python 中的 while
和 if
语句不使用外括号。这是 C 程序员遗留下来的坏习惯。