Skip to content

Race condition in Read on Windows #219

Description

@bminer

Describe the problem

The Read function uses the port.handle without a lock:

err = windows.ReadFile(port.handle, p, &readed, ev)

https://github.com/bugst/go-serial/blob/master/serial_windows.go#L88

But, Close could be called concurrently to cancel the Read, which sets port.handle. This is a race condition. The solution is to have Read only read the handle with a lock:

port.mu.Lock()
h := port.handle
port.mu.Unlock()
// later... we use the handle
err = windows.ReadFile(h, p, &readed, ev)

To reproduce

On Windows, call Close on the serial port during a pending Read. Be sure that the Go race detector is turned on.

Please double-check that you have reported each of the following

before submitting the issue.

  • I've provided the FULL source code that causes the problem
  • I've provided all the actions required to reproduce the problem

Expected behavior

No race.

Operating system and version

Windows 11 - go1.26.2 windows/amd64

Please describe your hardware setup

No response

Additional context

Related issue #105

Issue checklist

  • I searched for previous requests in the issue tracker
  • My request contains all necessary details

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions