2017-12-20 19 views
1

は、このthreading.Threadクラスを考えてみましょう:コンテキストマネージャでスレッドを使用するには?

class Sleeper(threading.Thread): 
    def __init__(self, sleep=5.0): 
     threading.Thread.__init__(self) 
     self.event = threading.Event() 
     self.sleep = sleep 

    def run(self): 
     while self.sleep > 0 and not self.event.is_set(): 
      self.event.wait(1.0) 
      self.sleep -= 1 

    def stop(self): 
     self.event.set() 

それは時間と終了の一定量のために眠るか、その量に達する前に停止しています。

私はそれを使用する:

sleeper = Sleeper() 
try: 
    sleeper.start() 
    # do stuffs here 
except: 
    # handle possible exceptions here 
finally: 
    sleeper.stop() 

そして、私はむしろ、コンテキストマネージャのようにそれを使用します。

with Sleeper(): 
    # do stuffs here 

withブロックを終了するときに、スレッドが停止しています。

私は__enter____exit__メソッドを追加しようとしているし、動作しているようですが、私はこれが移動するための方法であるか分からない:

def __enter__(self): 
    self.start() 
    return self 

def __exit__(self, type, value, traceback): 
    self.stop() 

しかし、私は本当によ私がここで何をしているのか分からない。それはどのように正しく行われるべきですか?

+0

あなたの質問は正確ですか?あなたは何をしようとしているのかの解決策を持っているようです。 –

+0

私の解決策は私が試しているコードです。問題はこれがどうやって正しく行われるべきかということです。 – Bastian

+0

このSleeperクラスのポイントは何ですか?あなたは何のために寝ていますか、なぜそれを行うには別のスレッドが必要ですか? –

答えて

0

aws関連の問題の背景が不足しているため、あなたの質問をよく理解していません。あなたが言及したのと同じように、文脈を使ってこれを行うことはできます。

import threading 
import time 


class Sleeper(threading.Thread): 
    def __init__(self, sleep=5.0): 
     threading.Thread.__init__(self, name='Sleeper') 
     self.stop_event = threading.Event() 
     self.sleep = sleep 

    def run(self): 
     print('Thread {thread} started'.format(thread=threading.current_thread())) 
     while self.sleep > 0 and not self.stop_event.is_set(): 
      time.sleep(1.0) 
      self.sleep -= 1 
     print('Thread {thread} ended'.format(thread=threading.current_thread())) 

    def stop(self): 
     self.stop_event.set() 

    def __enter__(self): 
     self.start() 
     return self 

    def __exit__(self, *args, **kwargs): 
     self.stop() 
     print('Force set Thread Sleeper stop_event') 


with Sleeper(sleep=2.0) as sleeper: 
    time.sleep(5) 

print('Main Thread ends') 

次の2つのケースをテストすることができます。1.メインスリープ時間が長くなります。2.スリーパースレッドのスリープパラメータが大きくなり、結果が2つになります。

あなたはまだメインとスリーパースレッドと対話したい場合は、あなたのコードがすべきは次のようになります。

with Sleeper(sleep=2.0) as sleeper: 
    cnt = 15 

    while cnt > 0 and sleeper.is_alive(): 
     print(cnt) 
     cnt -= 1 
     time.sleep(1) 

そして、あなたはメインだけのため、枕木に、いくつかの番号を印刷見ることができるには、端部を有し、もはや生きていない。

関連する問題