Merge branch 'fix-context-close-race' of https://github.com/krasin/gousb
This commit is contained in:
@@ -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)
|
||||
|
@@ -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())
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user