一旦列表的長度發生一定的變化,我可以觸發某些函數的有效方法是什麼?如何在滿足條件時觸發函數
我有一個嵌套列表,我每秒添加數據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