一旦列表的长度发生一定的变化,我可以触发某些函数的有效方法是什么?如何在满足条件时触发函数
我有一个嵌套列表,我每秒添加数据100次,并且我想在列表长度增加一些值时触发一个函数。我试图在while
循环内使用if
声明来执行此操作(请参见下面的my_loop()
)。这很有效,但这个看似简单的操作占用了我的一个CPU核心的100%。在我看来,不断查询列表大小是脚本的限制因素(将数据添加到while
循环中的列表不是资源密集型的)。
这里是我到目前为止已经试过:
from threading import Event, Thread
import time
def add_indefinitely(list_, kill_signal):
"""
list_ : list
List to which data is added.
kill_signal : threading.Event
"""
while not kill_signal.is_set():
list_.append([1] * 32)
time.sleep(0.01) # Equivalent to 100 Hz.
def my_loop(buffer_len, kill_signal):
"""
buffer_len: int, float
Size of the data buffer in seconds. Gets converted to n_samples
by multiplying by the sampling frequency (i.e., 100).
kill_signal : threading.Event
"""
buffer_len *= 100
b0 = len(list_)
while not kill_signal.is_set():
if len(list_) - b0 > buffer_len:
b0 = len(list_)
print("Len of list_ is {}".format(b0))
list_ = []
kill_signal = Event()
buffer_len = 2 # Print something every 2 seconds.
data_thread = Thread(target=add_indefinitely, args=(list_, kill_signal))
data_thread.start()
loop_thread = Thread(target=my_loop, args=(buffer_len, kill_signal))
loop_thread.start()
def stop_all():
"""Stop appending to and querying the list.
SO users, call this function to clean up!
"""
kill_signal.set()
data_thread.join()
loop_thread.join()
输出示例:
Len of list_ is 202
Len of list_ is 403
Len of list_ is 604
Len of list_ is 805
Len of list_ is 1006
Python的多线程不切换活动线程直到I/O需要地方或'time.sleep()'被称为当前正在运行的那个。这意味着你的代码大部分时间都在执行一个线程或另一个线程。 – martineau
谢谢。即使当我使用1 ms的睡眠持续时间('time.sleep(0.001)')时,这也是有效的。 – Jakub