从/sf/answers/22786991/尝试"可停止"的线程,如下所示:
import sys
import threading
import time
import logging
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
print( "base init", file=sys.stderr )
super(StoppableThread, self).__init__()
self._stop = threading.Event()
def stop(self):
print( "base stop()", file=sys.stderr )
self._stop.set()
def stopped(self):
return self._stop.is_set()
class datalogger(StoppableThread):
"""
"""
import time
def __init__(self, outfile):
"""
"""
StoppableThread.__init__(self)
self.outfile = outfile
print( "thread init", file=sys.stderr )
def run(self):
"""
"""
print( "thread …Run Code Online (Sandbox Code Playgroud) 我正在使用线程库,并且希望有一个线程可以调用多个线程。该程序的背景是我有一个摄像头,可以捕获Image并使它们在TCP-SocketServer的类中可用。
因此,我需要一个运行相机捕获的线程和另一个运行TCPServer的线程,但是在此线程中,每个进入的连接都有多个线程。
最后一个线程意味着我需要一个可以自己创建线程的线程。不幸的是,这没有用。
我设法将巨大的代码分解成一个小片段,代表了问题所在:
import threading
def adder(x,res,i):
res[i] = res[i] + x*i;
def creator(a,threads,results):
results = []
for i in range(0,a):
results.append(0)
threads.append(threading.Thread(target=adder,args=(a,results,i)))
threads[i].start()
for i in range(0,len(threads)):
threads[i].join()
return results;
threads = [];
results = [];
mainThread = threading.Thread(target=creator,args=([5,threads,results]))
mainThread.start()
mainThread.join()
for i in range(0,len(results)):
print results[i]
print threads[i]
Run Code Online (Sandbox Code Playgroud)
在creator称为线程的函数中,应该使用funciton创建多个线程adder。
但是结果是空的,为什么会这样呢?
这是我的较大程序中发生的相同问题。
为了简化我遇到的情况:我试图终止一个仍在 Python 2.7 中运行的线程,但我不知道该怎么做。
拿这个简单的代码:
import time
import threading
def thread1():
print "Starting thread 1"
while True:
time.sleep(0.5)
print "Working"
thread1 = threading.Thread(target=thread1, args=())
thread1.start()
time.sleep(2)
print "Killing thread 1"
thread2.stop()
print "Checking if it worked:"
print "Thread is: " + str(thread1.isAlive())
Run Code Online (Sandbox Code Playgroud)
线程 1 继续“工作”,我试图在主线程中杀死它。关于如何做到这一点的任何想法?我试过了:
threat1.terminate
threat1.stop
threat1.quit
threat1.end
Run Code Online (Sandbox Code Playgroud)
这一切似乎都表明,没有办法用一行简单的代码来真正阻止它。你有什么建议?
我需要一个装饰器(或功能等效的东西)来允许下面的代码按预期工作:
@timeout(1)
def outer():
inner()
@timeout(5)
def inner():
time.sleep(3)
print("Should never be printed if you call outer()")
outer()
# The outer timeout is ignored and "property" finishes
Run Code Online (Sandbox Code Playgroud)
该代码看起来毫无意义,但实际上,outer调用了多个函数,这些函数花费了不确定的时间,其中一些函数有自己的超时时间。
我在这里尝试了timeout-decorator和两个 SO 答案,但没有一个有效。
在线程中,我有一个循环从用户控制台读取输入。主线程忙于Tkinter mainloop()。如何终止该程序?
Run Code Online (Sandbox Code Playgroud)while True: ln = sys.stdin.readline() try: ln = ln[:-1] # Remove LF from line if len(ln)==0: continue # Ignore blank lines ...and so on主主题调用包含tk.mainloop()调用的startGUI()。当我按下窗口(这是Linux)上的X关闭按钮时,Tkinter关闭窗口,并且mainloop()返回。然后,我尝试关闭stdin,希望sys.stdin将关闭并导致sys.stdin.readline()将以一个不错的EOF终止,从而允许我的stdinLoop线程终止。
Run Code Online (Sandbox Code Playgroud)# Start up the GUI window startGUI() # Doesn't return until GUI window is closed, tk.mainloop is called here # # Wait for stdinLoop thread to finish sys.stdin.close() # Hopefully cause stdinTh to close print("waiting for stdinTh to join") stdinTh.join() print("joined stdinTh")
sys.stdin.realine()永远不会在sys.stdin.close()之后返回。(stdinTh.join()用于同步关闭。)
我认为Python readline()做的聪明的事情(在NetCommand中)在关闭stdin时不会干净地返回。
Python认为同时拥有Tkinter GUI和交互使用stdin 是否有害?
我尝试使用sys.stdin.read(1),但是似乎缓冲了一行并返回了整行-而不是像我认为的read(1)那样读取一个字节/字符。
这里发布了一个解决方案来创建一个可停止的线程。但是,我在理解如何实施此解决方案时遇到了一些问题。
使用代码...
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
Run Code Online (Sandbox Code Playgroud)
如何创建一个线程来运行每 1 秒向终端打印一次“Hello”的函数。5 秒后,我使用 .stop() 停止循环函数/线程。
我再次在理解如何实现这个停止解决方案时遇到了麻烦,这是我目前所拥有的。
import threading
import time
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def …Run Code Online (Sandbox Code Playgroud) 我已经使用一个Timer对象启动了一个线程.现在,我想停止这个线程,但我不能.我用过cancel(),但它不起作用.我不知道为什么.
import threading
import time
import sys as system
def Nop():
print("do nothing")
return 0
def function():
try:
while True:
print("hello world ")
time.sleep(2)
except KeyboardInterrupt:
print( "Good job!! exception catched")
t = threading.Timer(10, function)
t.start()
print(t.getName)
counter = 0
while True:
try:
time.sleep(1)
Nop()
counter = counter +1
print(counter)
if counter == 20:
print(t.getName)
t.cancel()
counter = 0
break
if t.is_alive() == False:
print("The Timer thread is dead...")
except KeyboardInterrupt:
print("End of program")
t.cancel()
system.exit(0) …Run Code Online (Sandbox Code Playgroud) 问题是我想杀死当前正在运行的所有线程。例如,我有一个调用 for 循环的按钮。突然间我想阻止它。
这是我的代码:
class WorkerThread(threading.Thread):
def __init__(self,t,*args):
super(WorkerThread,self).__init__(target=t,args=(args[0],args[3]))
self.start()
self.join()
Run Code Online (Sandbox Code Playgroud)
我的实现:
def running(fileopen,methodRun):
#....long task of code are here...
for file in fileTarget:
threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
Run Code Online (Sandbox Code Playgroud) 在这段代码中
杀=假
a = tr.Thread(target=func, args=(a, b, Kill), daemon=True)
a.start()
这是一个 tkinter 应用程序,所以我如何杀死这个线程,就像用什么命令来做到这一点。
python ×8
class ×1
decorator ×1
func ×1
kill ×1
python-2.7 ×1
python-3.4 ×1
python-3.x ×1
timeout ×1
timer ×1
tkinter ×1