How does Go runtime decide minimum number of threads?

842 views
Skip to first unread message

Rahul Tiwari

unread,
Jun 20, 2022, 6:27:12 PM6/20/22
to golang-nuts
I have intentionally set a max limit on the number of threads which can be spawned by my Go program to be 1 and the Go runtime errors out that it exceeds 1-thread limit.
I've checked the entire code of runtime but couldn't find how the minimum threshold of threads to be spawned is decided. Any pointers?

```
package main

import (
"fmt"
"runtime/debug"
)

func main() {
debug.SetMaxThreads(1)
fmt.Println("Hello world!")
}
```



Ian Lance Taylor

unread,
Jun 20, 2022, 6:43:58 PM6/20/22
to Rahul Tiwari, golang-nuts
On Mon, Jun 20, 2022 at 3:27 PM Rahul Tiwari <jprrahu...@gmail.com> wrote:
>
> I have intentionally set a max limit on the number of threads which can be spawned by my Go program to be 1 and the Go runtime errors out that it exceeds 1-thread limit.
> I've checked the entire code of runtime but couldn't find how the minimum threshold of threads to be spawned is decided. Any pointers?

There is no minimum threshold of threads as such. But the scheduler
will at the very least start a new thread to run the system monitor,
which runs the sysmon function in runtime/proc.go. So 2 is a absolute
minimum for the number of threads. And if a thread blocks in a system
call, and there are other goroutines waiting to run, the system
monitor thread will start another thread to run those goroutines.
This decision to start a new thread does not look at the limit set by
runtime/debug.SetMaxThreads. The SetMaxThreads function is intended
to stop a runaway program from taking down the entire system. It's
not intended to limit a Go program to using a very small number of
threads. Go programs are always inherently multi-threaded.

Ian

Sean Liao

unread,
Jun 20, 2022, 8:38:04 PM6/20/22
to golang-nuts
from runtime:

> The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit.

- sean

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/3c14a0f8-7363-4183-9b0d-781d72e6ef8fn%40googlegroups.com.

TheDiveO

unread,
Jun 21, 2022, 2:35:04 AM6/21/22
to golang-nuts
additionally, threads (m's) currently locked to goroutines using runtime.LockOSThread don't count either.
Reply all
Reply to author
Forward
0 new messages