Priority of go routines

Go seems to execute go routines in a random order.
Most of the time I’m fine with that, but in some special cases I want to start a go routine with a higher priority.
Is this possible, without coding/using an elaborate or overheaded task assigner?

No.

1 Like

I agree but let’s be a bit more constructive: if you buffer a channel you can decrease the amount of switching between goroutines and that might be a desired property.

But it’s not priority: let the scheduler decide that. At runtime, it has a much clearer picucture of the goroutines that need to run (and the number of processors on which to run on, etc.)

2 Likes

What do you mean by “higher priority”?

  • If a piece of code must run before some other parts of the code, simply serialize it. (Either by using channels or other means of synching, or by not using concurrency at all.)

  • If a specific goroutine shall have a higher chance of executing than others (similar to prioritie of OS processes), then you indeed need to build your own scheduler/prioritizer. This is not part of the concurrency model. (And then I would be curious about your use case.)

4 Likes

E.g. I’m listening to a serial port with a blocking b, err := p.Read(buff). Sometimes it skips one or two bytes because the scheduler decides to run other routines first, at just 4800 baud. I’m scared what will happen at 115200 baud …

I see what you mean.

Go itself is not suited for hard real-time systems where missing a deadline is a failure. Not only other goroutines can delay the responsiveness of the goroutine that listens on the serial port; the garbage collector can also introduce delays, as well as the operating system when scheduling processes.

Usually, I would assume that it should be the serial port driver’s duty to buffer the incoming data until the consumer is ready to read them (and tell the sender to pause if the buffer is full). A serial driver, being a low-level component of the OS, should be able to react on incoming data the moment it arrives.

Did you look at projects such as GoBot already? I guess projects like this one have solved that issue already in some way (maybe even available as a ready-to-go package).

1 Like

another project to look at is https://periph.io/ (which exposes a slightly more Go-idiomatic API than GoBot, IMHO. But GoBot is really nice!)

2 Likes

I wonder if using multiple channels to segment the intake of data and the operational output by taking data from your serial into one channel and then passing it to another where your other routines work on it would be something that would help your needs. https://blog.golang.org/share-memory-by-communicating

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.