Pythonのスレッドの子スレッドが終了し、終了の制御コード

プログラマーの数は公的機関に集中できるように、csdn2299:@この記事は、公開番号から来ています

この記事では、子スレッド終了Pythonコードとスレッド終了制御を導入し、非常に良い、参照のための特定の値を持って、困っている友達は、参照することができ
、次のPythonの問題子スレッドの終了コードを導入し、以下に示します:

def thread_func():
  while True:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# main thread do something
# main thread do something
# main thread do something

アップを実行しても問題ありませんが、Ctrl + C割り込み問題、メインスレッドが終了、しかし、子スレッドを使用する際にまだ実行されています。

こうしてメインスレッドコード信号処理の増加は、レシートSIGINT時子スレッドループ条件を変更します

loop = True
def thread_func():
  while loop:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# ctrl+c时,改变loop为False
def handler(signum, frame):
  global loop
  loop = False
  t.join()
  exit(0)
signal(SIGINT, handler)
# main thread do something
# main thread do something
# main thread do something

このような出口まで+ C、Ctrlが、メインスレッドは、プロセスが終了しないだろうから出ていることは間違い?

Pythonのスレッドの終了点広がり知識制御

ctypesのモジュール制御スレッド終了

Pythonはモジュールをスレッドとスレッドが終了するの設計の機構がない、その理由は、スレッドの終了は、意図しない結果につながる可能性のいずれかの正常ではありません。

例えば:

スレッドは、ロックを正しいキーを解放しなければならないリソースを保持しています。

子スレッドのスレッドの作成、だけでなく、それは殺されます。

管理自身のスレッドは、最善のアプローチは、一定の時間間隔に基づいて、各スレッドは、彼らが終了する必要があるかどうかを確認するためのルールをチェックするように、誘導灯の要求を持っていることです。

次のコード例:

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()

スレッド内のコードは定期的にあなたがストップ()関数を呼び出すことができ、終了時には、一時停止の標識をチェックし、出口にスレッドを待つために参加する()関数を使用する必要があります。

しかし、実際にスレッドを殺したい事情があるかもしれない、例えば、あなたが長い時間のために忙しく、それを呼び出し、外部ライブラリパッケージであり、あなたはそれを破るしたいと思います。

Pythonのスレッドは例外を投げることができます。

パラメータ渡しは、スレッドID番号であり、識別を撤回します

def _async_raise(tid, exctype):
  '''Raises an exception in the threads with id tid'''
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
                         ctypes.py_object(exctype))
  if res == 0:
    raise ValueError("invalid thread id")
  elif res != 1:
    # "if it returns a number greater than one, you're in trouble,
    # and you should call it again with exc=NULL to revert the effect"
    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")

それが例外をスロー割り込みPythonインタプリタ外で実行中のスレッドは、それがキャプチャしない場合は、スレッドが中断することはできません。

簡略化した後、上記のコードは、スレッドへの割り込みで実用に適用することができ、実行中のスレッドは、しばしばそれ自体の上、例えば許容範囲のために、検出されました。

def _async_raise(tid, exctype):
  """raises the exception, performs cleanup if needed"""
  tid = ctypes.c_long(tid)
  if not inspect.isclass(exctype):
    exctype = type(exctype)
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  if res == 0:
    raise ValueError("invalid thread id")
  elif res != 1:
    # """if it returns a number greater than one, you're in trouble,
    # and you should call it again with exc=NULL to revert the effect"*斜体样式*""
    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
    raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
  _async_raise(thread.ident, SystemExit)

読むためにありがとうございまし
作業コンピューターの基本的な悪い損失を食べて、これが教育を受けていないことが判明し、自己のpythonを、選んだ大学で
唯一補うために取得することができ、できないこと、そして、コーディング外で彼自身のカウンター攻撃をオープンしました道路、常にあなたが平凡に不本意であれば、それは外に成長している、コーディングの私と一緒で、Pythonのコア知識、基本的なコンピュータ学習の深い知識、組織化を学びます!
実際には、それよりも技術的な、より技術的なものではないだけであり、例えば、プログラマ自身が高貴な存在である、ああ、それはどのようにではなく、「巨根ワイヤー」よりも、細かなプログラマを作ることではないでしょうか?[参加するためにクリック]、あなたは高貴な人になりたいたい給油

公開された61元の記事 ウォン称賛22 ビュー40000 +

おすすめ

転載: blog.csdn.net/haoxun02/article/details/105316592