diff --git a/usb/usb.go b/usb/usb.go index 1dace5d..cf820a9 100644 --- a/usb/usb.go +++ b/usb/usb.go @@ -27,7 +27,7 @@ import ( type Context struct { ctx *C.libusb_context - done chan struct{} + done chan bool } func (c *Context) Debug(level int) { @@ -36,7 +36,7 @@ func (c *Context) Debug(level int) { func NewContext() *Context { c := &Context{ - done: make(chan struct{}), + done: make(chan bool), } if errno := C.libusb_init(&c.ctx); errno != 0 { @@ -44,13 +44,14 @@ func NewContext() *Context { } go func() { + tv := C.struct_timeval{0, 100000} for { select { case <-c.done: return default: } - if errno := C.libusb_handle_events(c.ctx); errno < 0 { + if errno := C.libusb_handle_events_timeout_completed(c.ctx, &tv, nil); errno < 0 { log.Printf("handle_events: error: %s", usbError(errno)) continue } @@ -103,6 +104,7 @@ func (c *Context) ListDevices(each func(desc *Descriptor) bool) ([]*Device, erro } func (c *Context) Close() error { + c.done <- true close(c.done) if c.ctx != nil { C.libusb_exit(c.ctx) diff --git a/usb/usb_test.go b/usb/usb_test.go index abab837..78c4159 100644 --- a/usb/usb_test.go +++ b/usb/usb_test.go @@ -15,6 +15,9 @@ package usb_test import ( + "bytes" + "log" + "os" "testing" . "github.com/kylelemons/gousb/usb" @@ -77,3 +80,22 @@ func TestEnum(t *testing.T) { } } } + +func TestMultipleContexts(t *testing.T) { + var buf bytes.Buffer + log.SetOutput(&buf) + for i := 0; i < 10; i++ { + ctx := NewContext() + _, err := ctx.ListDevices(func(desc *Descriptor) bool { + return false + }) + if err != nil { + t.Fatal(err) + } + ctx.Close() + } + log.SetOutput(os.Stderr) + if buf.Len() > 0 { + t.Errorf("Non zero output to log, while testing: %s", buf.String()) + } +}