我正在Raspberry Pi 2上進行一個rospy項目。 pyhton腳本需要在接收到消息時啓動一個線程,並循環它直到另一個消息接收。 但是由於這些線程需要訪問硬件,所以每次收到新消息時都應該停止舊線程。 我建立了我自己的鎖定系統,但是當充斥着消息時它失敗了。 現在我正在研究信號量,但要麼我不太瞭解它們的工作方式,要麼我需要別的東西,但類似於信號量。需要跳出「無限循環」的信號量對象
目前我的代碼看起來是這樣的:
def some_thread():
# lock_int is 0 when noone uses the hardware, 1 when another thread uses it
global lock_int
# my way of signaling that I want to get the Hardware access
lock_int += 1
# wait until other thread releases Hardware
while(lock_int > 1):
wait()
# loop until some other thread requests hardware
while(lock_int < 2)
do_hardware_stuff()
# release hardware
lock_int -= 1
如果我想用旗語要做到這一點,我需要某種信號在do_hardware_stuff循環看到該請求。 事情是這樣的:
def semaphore_thread():
# blocking request, waits until other thread releases
semaphore.acquire()
# loop until some other thread requests hardware
while(semaphore.got_request() != True)
do_hardware_stuff()
# release hardware
semaphore.release()
有沒有一種方法,我可以用旗語或類似的這樣的對象?
感謝, ChTe
但是,這不會循環do_harware_stuff()部分。 主要問題是在循環中獲取某種通知以跳出並釋放硬件。 – ChTe