鉴于此代码段:
import time
if __name__ == "__main__":
list = []
counter = 0
while True:
counter = counter + 1
time.sleep(0.0033)
list.append(counter)
我想创建一个在后台运行的线程,在数组上执行一些元数据计算(查找数组中元素的总和)" list"在while循环中实时填充。
答案 0 :(得分:0)
import time
import threading
if __name__ == "__main__":
def print_sum(l):
while True:
total = sum(l)
print("the total is {}".format(total))
time.sleep(1)
#list = [] - should not use 'list'. - this shadows the built in object name list.
l = []
counter = 0
thread = threading.Thread(target=print_sum,args=(l,))
thread.daemon = True
thread.start()
while True:
counter = counter + 1
l.append(counter)
time.sleep(1)
这会在后台运行函数print_sum
中旋转一个线程,以显示列表的总和。