我有兩個線程。第一個(update_ds())從服務器獲取數據並存儲在全局變量(ds)中。第二個線程(ldk_modes())使用來自第一個線程的數據並相應地執行操作。這是這樣的:python爲什麼在一個線程中真正阻塞另一個線程
def update_ds():
global ds
try:
ds = get_data(5)
print (ds)
except:
print('update error')
pass
#runs every 1 second
threading.Timer(1, update_ds).start()
def ldk_modes():
global old_ds
old_ds = ds
while True:
if ds != old_ds:
if ds == 1003:
do_something()
old_ds = ds
elif ds == 1002:
do_something_else()
old_ds = ds
else:
pass
update_ds()
threading.Thread(target=ldk_modes).start()
我的第一個問題是,我從update_ds()打印出來不打印每一秒。 do_something()或do_something_else()也不會很快響應服務器數據更新(我猜這最終是update_ds()線程每秒不更新的結果)。爲什麼?
早些時候,我的代碼的另一個版本:
ds = 0
old_ds = 0
def update_ds():
global ds
try:
ds = get_data(5)
print (ds)
except:
print('update error')
pass
#runs every 1 second
threading.Timer(1, update_ds).start()
def ldk_modes():
global old_ds
while True:
if ds != old_ds:
if ds == 1003:
do_something()
old_ds = ds
elif ds == 1002:
do_something_else()
old_ds = ds
update_ds()
threading.Thread(target=ldk_modes).start()
我有打印(DS)同樣的問題不每秒執行一次。但是,如果我做「ctrl + c」,儘管我無法終止程序,但我能夠每秒打印一次print(ds)!爲什麼?什麼是終止程序的正確方法?現在,我使用sudo kill processID,這有點不方便。
最後,什麼是
def thread_fn():
while True:
print("hello")
threading.Thread(target=thread_fn).start()
和
def thread_fn():
print("hello")
threading.Thread(target=thread_fn).start()
兩者之間的差異將創建一個運行無限線程,是一個比其他更好嗎?謝謝!
我沒有看到在python中使用線程的任何理由,它永遠不會像單線程程序那樣執行,並且通常由於[GIL](https://wiki.python.org/moin)/GlobalInterpreterLock) – alfasin
@alfasin在我的較大程序中,我有多個線程,如3個線程獲取信息,以及5個線程使用這3個線程的信息來執行任務。它們不能合併,因爲我無法在所有線程中以相同的速率從服務器檢索信息。在這裏,我只寫了一個較小的程序,以確保在我花費太多時間編寫最終程序之前正確理解事情。 –
如果是通過網絡檢索信息然後處理它,通常最好使用多個進程和IPC而不是蟒蛇,而不是貧困線程設施。 – pvg