2017-09-23 29 views
0

クラスにはさまざまな機能があります。別のクラスの別のファイルでは、メッセージをキャッチしてguiに印刷したいと思います。私は次のコードを持っているシミュレーションとして :私が欲しいもの2つの機能を別々のクラスに同期させる

import threading 
import time 
import logging 

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) 

message = None 


def messages_generator(condition): 
    global message 
    with condition: 
     logging.debug('Condition: {}'.format(condition)) 
     for i in range(5): 
      message = 'i = ' + str(i) 
      time.sleep(1) 
      logging.debug('Condition wait') 
      condition.wait() 


def messages_sow(condition): 
    global message 
    with condition: 
     print(message) 
     logging.debug('Condition notify') 
     condition.notify() 
    logging.debug('Tread finished') 


condition = threading.Condition() 
messages_generator_thread = threading.Thread(name='Message Generator', target=messages_generator, args=(condition,)) 
messages_sow_thread = threading.Thread(name='Message Sow', target=messages_sow, args=(condition,)) 

messages_generator_thread.start() 
messages_sow_thread.start() 

messages_sow強調テキストで印刷するメッセージを待機し、それが完了するまで継続するmessages_generatorです。上記のコードを実行すると、プログラムは2番目の '条件待ち'でフリーズします。 歓迎すべきアドバイス。

答えて

0

私は最終的に上記のコードを操作することができましたが、Model - View - Controllerプログラミングモデルに基づいて開発した基本的なプログラムでは動作しませんでした。 私は動作するコードを引用します。

import threading 
import time 
import logging 

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) 

message = None 


def messages_generator(condition): 
    logging.debug('--- Start ---') 
    global message 
    messages_number = 5 
    for i in range(messages_number): 
     logging.debug('Inside For. i = {}'.format(i)) 
     condition.acquire() 
     if message is not None: 
      logging.debug('Condition wait') 
      condition.wait() 
     if i == (messages_number - 1): 
      message = 'end' 
      logging.debug('Message = {}'.format(message)) 
     else: 
      message = 'i = ' + str(i) 
      time.sleep(1) 
     logging.debug('Condition notify') 
     condition.notify() 
     logging.debug('Condition release') 
     condition.release() 

def messages_sow(condition): 
    logging.debug('--- Start ---') 
    global message 
    while True: 
     logging.debug('Inside While. stop = {}'.format(True)) 
     condition.acquire() 
     if message is None: 
      logging.debug('Condition wait') 
      condition.wait() 
     else: 
      print(message) 
     if message == 'end': 
      break 
     message = None 

     condition.notify() 
     condition.release() 
    logging.debug('Tread finished') 


condition = threading.Condition() 
messages_generator_thread = threading.Thread(name='Message Generator', target=messages_generator, args=(condition,)) 
messages_sow_thread = threading.Thread(name='Message Sow', target=messages_sow, args=(condition,)) 

messages_generator_thread.start() 
messages_sow_thread.start() 
関連する問題