Pythonのプログラミングでは、私が呼び出すときに関数や何かを実行するとコードが進行しないようにするのが一般的です。だから私はブロックを解除する最善の方法はスレッドを使用していると思うが、もし私が何をすべきかスレッドを停止する必要がありますか? 私はthis referenceを試してみましたが、私はこの簡単なプログラムを書いた:Pythonのkill関数を持つ非ブロックのスレッド
import threading
from time import sleep
class my_thread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(my_thread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
print("stopping the thread")
self._stop_event.set()
def stopped(self):
value=self._stop_event.is_set()
print("value of stop event is",value)
return value
def run(self):
print("running the thread")
print("start function startt()")
self.startt()
def startt(self):
print("it is going to wait forever")
while True:
#wait forever
pass
print("This line never execute")
def main():
for i in range(0,3):
print("it is the main function")
sleep(1)
if __name__+'__main__':
thr=my_thread()
thr.start()
sleep(5)
thr.stop()
thr.stopped()
print("calling the main function")
main()
print("Exiting the whole program")
私の問題は、このプログラムは、実際にスレッドを停止するが、プログラムがまだ実行され、最後の行を印刷した後です。私が望むのは、私が停止機能を呼び出すと、それはスレッドを起動して#wait forever line
を実行し、停止機能を呼び出すとthr.stop()
はクラス全体を停止し、#wait forever line
からmain関数に戻ります。
EDIT-- 私はそれを修正することができますが、私はこのコードの代わりに、while True
あったら私の問題は、例えば、一般的である@a_guest答えとして:
pythoncom.PumpMessages()
(または他のコード)
を何私はする必要がありますか?
あなたがしたいことは、 'while true'の代わりにあなたのイベントをチェックすることです。あなたが応答停止を望むならば、3'rdパーティブロッキングコールを使用することはできません。 'something.isthereanythingtodo()の代わりにsomething.do()else loop'のようなAPIをブロックする – user3012759