需要跳出 "infinite loop" 的类似信号量的对象
Semaphore-like object for jumping out of "infinite loop" needed
我正在 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
您可以启动更多线程并使用 threading.Lock
进行线程同步。
例如:
import threading
lock = threading.Lock()
def semaphore_thread():
lock.acquire()
try:
do_hardware_stuff()
finally:
lock.release()
我通过对硬件作业使用队列来修复它。
我在队列周围加了一把锁,以避免同时从不同的地方编辑队列。
我保留了我的 lock_int 机制,但由于我是 运行 在从队列中开始新作业之前的一个 kill 线程函数,
我可以保证只有一份工作运行.
def kill_thread():
global lock_int
lock_int += 1
while(lock_int > 1):
wait()
lock_int -= 1
我正在 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
您可以启动更多线程并使用 threading.Lock
进行线程同步。
例如:
import threading
lock = threading.Lock()
def semaphore_thread():
lock.acquire()
try:
do_hardware_stuff()
finally:
lock.release()
我通过对硬件作业使用队列来修复它。 我在队列周围加了一把锁,以避免同时从不同的地方编辑队列。 我保留了我的 lock_int 机制,但由于我是 运行 在从队列中开始新作业之前的一个 kill 线程函数, 我可以保证只有一份工作运行.
def kill_thread():
global lock_int
lock_int += 1
while(lock_int > 1):
wait()
lock_int -= 1