gpt4 book ai didi

python - 线程应用程序的信号量同步失败,Python

转载 作者:行者123 更新时间:2023-12-01 05:11:28 26 4
gpt4 key购买 nike

我正在构建一个 GUI 应用程序,用于与数字泵进行串行通信。我陷入了用于从中获取信息的更新机制。使用 QTimer(来自 PySide 模块)每 5 秒调用一次 update_values 方法,但用户可以通过调用相同的方法来专门订购更新。出于这个原因,我只希望一个线程在 update_values 代码上运行。然而,这似乎无法使用信号量或锁来工作,因为多个线程随意进入信号量 block :

self.update_sema = threading.Semaphore(value=1)

......

def update_values(self, initialize = False):
"""This is the parameters update method."""

self.update_sema.acquire(False)
print "ENTERED THE SEMAPHORE"
self.update_thread = threading.Thread(\
target = self.actual_update_method,\
args = (initialize,))
self.update_thread.start()
def actual_update_method(self, initialize):

# reading info mechanism
self.status["absolute_pos"] = self.send_Command('?', 10)[3:]
self.status["actual_pos"] = self.send_Command('?4', 10)[3:]
self.status["starting_vel"] = self.send_Command('?1', 10)[3:]
self.status["top_vel"] = self.send_Command('?2', 10)[3:]
self.status["cutoff_vel"] = self.send_Command('?3', 10)[3:]
self.status["backlash_steps"] = self.send_Command('?12', 10)[3:]
self.status["fluid_sensor"] = self.send_Command('?22', 10)[3:]
self.status["buffer_status"] = self.send_Command('?F', 10)[3:]

# These must be asked only once, at the initialization phase
if initialize:
#print "version set as well!"
self.status["version"] = self.send_Command('?&', 10)[3:]
self.status["checksum"] = self.send_Command('?#', 10)[3:]

self.update_sema.release()
print "EXITED THE SEMAPHORE"

最佳答案

由于您使用的是非阻塞调用 acquire(通过使用 acquire(blocking=False)),因此您需要确保仅在如果您实际获取了信号量,则该方法如下:

def update_values(self, initialize = False):
"""This is the parameters update method."""

if self.update_sema.acquire(False):
print "ENTERED THE SEMAPHORE"
self.update_thread = threading.Thread(\
target = self.actual_update_method,\
args = (initialize,))
self.update_thread.start()

documentation 中描述了此行为:

acquire([blocking])

When invoked without arguments: if the internal counter is larger thanzero on entry, decrement it by one and return immediately. If it iszero on entry, block, waiting until some other thread has calledrelease() to make it larger than zero. This is done with properinterlocking so that if multiple acquire() calls are blocked,release() will wake exactly one of them up. The implementation maypick one at random, so the order in which blocked threads are awakenedshould not be relied on. There is no return value in this case.

When invoked with blocking set to true, do the same thing as whencalled without arguments, and return true.

When invoked with blocking set to false, do not block. If a callwithout an argument would block, return false immediately; otherwise,do the same thing as when called without arguments, and return true.

关于python - 线程应用程序的信号量同步失败,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24150271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com