gpt4 book ai didi

python - 两个线程,一个对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:38 25 4
gpt4 key购买 nike

我正在用 Python 为 USB HID 设备编写 Linux 驱动程序。设备有两种发送数据的方式,这两种方式都是必需的:功能报告(同步)和输入报告(异步)。使用 hidapi Cython 库,我只有一个设备实例可以使用,但我需要为 hid.read() 设置一个监听器,它将持续运行并允许应用程序随意调用同步方法以发送功能报告。

目前我在一个线程中有监听器,在另一个线程中有同步调用。当我运行该程序时,我的同步调用没有发生,尽管如果我从不启动监听器它们可以正常工作;所以看起来监听器线程正在接管。

下面是令人不安的一段代码:

app.py

# app.py
import threading
import time
import myhiddriver

# Code that sets mydevice

class Reader:
def start(self, device):
self.requests = myhiddriver.DeviceRequest(device)
# Wait a bit before firing, for testing
time.sleep(3)
self.requests.request_swipe_card()

def start_listener(self, device):
self.listener = myhiddriver.DeviceListener(device)

reader = Reader()
thread1 = threading.Thread(target=reader.start, args=(mydevice,))
thread1.daemon = True
thread2 = threading.Thread(target=reader.start_listener, args=(mydevice,))
thread2.daemon = True
thread1.start()
thread2.start()

# Keep this puppy running
while True:
pass

myhiddriver.py

import threading

LOCK = threading.Lock()

class DeviceRequest:
def __init__(self, device):
# Lock it up first
LOCK.acquire()
self.device = device
LOCK.release()

def request_swipe_card(self):
# Lock this up too
LOCK.acquire()
self.device.set_feature_report(insert data here)
LOCK.release()

class DeviceListener:
def __init__(self, device):
# Lock me up
LOCK.acquire()
self.device = device
self.start_listener()
LOCK.release()

def start_listener(self):
while True:
# Should I be locking this up?
LOCK.acquire()
data = self.device.read(255)
LOCK.release()
if data:
print data
else:
pass

我的问题:为什么我的同步调用 (request_swipe_card) 没有跟进?或者,我怎样才能更好地构建它以拥有无穷无尽的监听器以及对同一对象进行同步调用的能力?

最佳答案

从代码上看,是因为你把它锁住了

When the state is unlocked, acquire() changes the state to locked and returns immediately. When the state is locked, acquire() blocks until a call to release() in another thread changes it to unlocked

问题是:

class DeviceListener:
def __init__(self, device):
LOCK.acquire() # first you lock it up
self.device = device
self.start_listener()
LOCK.release()

def start_listener(self):
while True: # because of the loop, the lock wouldn't get release even if the LOCK below doesn't exist
LOCK.acquire() # it end up blocking here and oops, it locked up xD
data = self.device.read(255) # so it wouldn't be able to read here
LOCK.release()
if data:
print data
else:
pass

request_swipe_card 最终在另一个线程中被调用时,它最终也会在那里阻塞

  def request_swipe_card(self):
LOCK.acquire() # right here xD
self.device.set_feature_report(insert data here)
LOCK.release()

关于python - 两个线程,一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821928/

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