将两个函数同步到单独的类中

时间:2017-09-23 21:04:57

标签: multithreading python-3.x thread-synchronization

在课堂上有不同的功能。在另一个类的单独文件中,我想捕获消息并打印到gui。 作为模拟,我有以下代码:

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_generator等待messages_sow强调文字打印的消息,并一直持续到完成为止。当我运行上面的代码时,程序冻结了第二个条件等待'。 任何建议都欢迎。

1 个答案:

答案 0 :(得分:0)

我终于设法完成了上面的代码,但没有基于模型 - 视图 - 控制器编程模型开发的基本程序。 我引用有效的代码。

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