2016-12-06 33 views
0

我正在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

回答

0

我通過使用隊列的硬件作業固定它。 我在隊列周圍放置了一個鎖,以避免在不同的地方同時編輯隊列。 我離開了我的lock_int機制,但由於我在開始一個新的作業之前運行殺線程函數,我可以保證只有一個作業正在運行。

def kill_thread(): 
    global lock_int 

    lock_int += 1 

    while(lock_int > 1): 
     wait() 

    lock_int -= 1 
0

,你可以啓動多個線程,並使用threading.Lock做線程同步。

例如:

import threading 
lock = threading.Lock() 

def semaphore_thread(): 

    lock.acquire() 
    try: 
     do_hardware_stuff() 
    finally: 
     lock.release() 
+0

但是,這不會循環do_harware_stuff()部分。 主要問題是在循環中獲取某種通知以跳出並釋放硬件。 – ChTe