我正在运行输出到控制台的线程。
要知道何时输出到控制台我使用监听器进行变量更改。
但是那个听众在循环中燃烧了很多处理能力。是否有更有效的方式来倾听变化?
以下是代码:
def output_console_item(message, sound=None, over_ride_lock=False):
log = StandardLogger(logger_name='output_console_item')
# lock to serialize console output
lock = threading.Lock()
def print_msg(message):
# Wait until console lock is released.
if over_ride_lock is False:
while True:
if CONSOLE_CH.CONSOLE_LOCK is False:
break
# time.sleep(0.10)
# Make sure the whole print completes or threads can mix up output in one line.
with lock:
print(message)
return
thread = Thread(target=print_msg, args=(message,))
thread.start()
thread.join()
if sound:
thread = Thread(target=play_sound, args=(sound,))
thread.start()
thread.join()
答案 0 :(得分:1)
你不需要另一个线程为你打印东西,
您可以创建安全的打印,例如
lock = threading.Lock()
def safe_print(message):
with lock:
print message
并在所有线程中使用它
甚至更好地使用已经线程安全的python模块日志记录
编辑:
您可以将CONSOLE_LOCK更改为真正的锁定 并使用类似这样的东西
def print_msg(message):
# Wait until console lock is released.
if over_ride_lock is False:
with CONSOLE_LOCK:
pass
with lock:
print(message)
而不是做CONSOLE_LOCK = True做CONSOLE_LOCK.acquire而不是做CONSOLE_LOCK = False做CONSOLE_LOCK.release()