fix life manager of libusb_device*

This commit is contained in:
gb 2023-11-24 15:14:15 +08:00
parent 89b2fc4777
commit 2400239e55
1 changed files with 11 additions and 2 deletions

View File

@ -70,7 +70,7 @@ int LIBUSB_CALL usb_manager::usb_pnp_callback(libusb_context* ctx, libusb_device
usb_manager* obj = (usb_manager*)monitor; usb_manager* obj = (usb_manager*)monitor;
// if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) // if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)
libusb_ref_device(device); // keep the object until handle it //libusb_ref_device(device); // keep the object until handle it
//else if(event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) //else if(event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
// libusb_unref_device(device); // libusb_unref_device(device);
@ -187,17 +187,22 @@ void usb_manager::thread_notify_usb_event()
} }
} }
libusb_ref_device(pd.dev); // for re-enter the queue pnp_events_
notify_usb_event(pd, &retry); notify_usb_event(pd, &retry);
if (retry) if (retry)
{ {
if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - pd.happen_time).count() if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - pd.happen_time).count()
<= 5000) <= 5000)
pnp_events_.Put(pd, sizeof(pd)); pnp_events_.Put(pd, sizeof(pd));
else
retry = false;
if(pnp_events_.Size() == 1) if(pnp_events_.Size() == 1)
this_thread::sleep_for(chrono::milliseconds(1000)); this_thread::sleep_for(chrono::milliseconds(1000));
else else
this_thread::sleep_for(chrono::milliseconds(delay)); this_thread::sleep_for(chrono::milliseconds(delay));
} }
if (!retry)
libusb_unref_device(pd.dev);
} }
} }
} }
@ -283,6 +288,7 @@ int usb_manager::on_usb_pnp_event(libusb_context *ctx, libusb_device *device, li
PNPDEV pd; PNPDEV pd;
unsigned ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - born_).count(); unsigned ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - born_).count();
libusb_ref_device(device);
pd.ctx = ctx; pd.ctx = ctx;
pd.dev = device; pd.dev = device;
pd.event = event; pd.event = event;
@ -295,9 +301,12 @@ int usb_manager::on_usb_pnp_event(libusb_context *ctx, libusb_device *device, li
else else
{ {
bool retry = false; bool retry = false;
libusb_ref_device(device);
notify_usb_event(pd, &retry); notify_usb_event(pd, &retry);
if(retry) if(retry)
pnp_events_.Put(pd, sizeof(pd)); pnp_events_.Put(pd, sizeof(pd));
else
libusb_unref_device(device);
} }
return 0; return 0;