Python线程问题 - 将控制权返回给父进程
基本上,我有一个Python程序,它会监听设备添加的DBus事件(比如说,当有人插入USB驱动器时)。当发生这样的事件时,我想创建一个线程来收集新连接设备的元数据。不过,我希望这个过程是异步的,也就是说,我希望一个线程可以继续收集设备的元数据,同时把控制权交还给主程序,这样主程序就可以继续监听这些事件。目前,我的线程在收集完成之前是会阻塞的。以下是我的代码示例:
class DeviceAddedListener:
def __init__(self):
self.bus = dbus.SystemBus()
self.hal_manager_obj = self.bus.get_object("org.freedesktop.Hal", "/org$
self.hal_manager = dbus.Interface(self.hal_manager_obj, "org.freedeskto$
self.hal_manager.connect_to_signal("DeviceAdded", self._filter)
def _filter(self, udi):
device_obj = self.bus.get_object ("org.freedesktop.Hal", udi)
device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device")
if device.QueryCapability("volume"):
return self.capture(device)
def capture(self,volume):
self.device_file = volume.GetProperty("block.device")
self.label = volume.GetProperty("volume.label")
self.fstype = volume.GetProperty("volume.fstype")
self.mounted = volume.GetProperty("volume.is_mounted")
self.mount_point = volume.GetProperty("volume.mount_point")
try:
self.size = volume.GetProperty("volume.size")
except:
self.size = 0
print "New storage device detected:"
print " device_file: %s" % self.device_file
print " label: %s" % self.label
print " fstype: %s" % self.fstype
if self.mounted:
print " mount_point: %s" % self.mount_point
response = raw_input("\nWould you like to acquire %s [y/N]? " % self.device_file)
if (response == "y"):
self.get_meta()
thread.start_new_thread(DoSomething(self.device_file))
else:
print "Returning to idle"
if __name__ == '__main__':
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
DeviceAddedListener()
loop.run()
任何想法都非常欢迎 :) 我省略了导入列表以节省空间。
1 个回答
2
试着为捕获的部分单独创建一个线程,可以把你在 _filter()
函数中的以下几行改成这样:
if device.QueryCapability("volume"):
threading.start_new_thread(self.capture, (device))
这里假设大部分工作都是在 capture()
函数中完成的。如果不是,那就可以在更早的时候创建线程,可能是在整个 _filter()
函数开始的时候。这样的话,每当检测到一个被过滤的设备时,就会为它创建一个新的线程。需要注意的是,我没有做过任何关于 dbus 的操作,也不能真正测试这个,但这是一个想法。
另外,你在捕获函数中试图获取用户输入,而根据你定义的应用,这在多线程中并不是个好主意。如果在第一个提示还在屏幕上时,第二个设备连接上来了,那可能会出现问题。
这个设计可能是出于某些特定原因而这样做的,但我总觉得它可以做得更流畅。从我能看出来的,它并不是特别考虑到多线程的设计。