Threads and cores


(cinematik) #1

Is it true that different runned threads will be executed in different processor’s cores? For instance, there are four cores in processor and we start three threads. Does it mean that each thread will run in its own processor’s core and the last one core is not touched?

On the other side, what will happen if the number of thread is bigger than the number of cores? One thread - one core, and others will be distributed across all cores? Or they all will be distributed acros all available cores?


(ravuri sai ram akhil) #2

No. Go uses concurrency in compiling the go routines. You can look this for more info (https://medium.com/rungo/achieving-concurrency-in-go-3f84cbf870ca).


(Giulio Iotti) #3

Cores, threads and goroutines are all decoupled from each other.

Go will try to run at least one thread per core by default. You will probably end up having more threads than cores: for example if you read a file, there will be a thread blocked reading the file. This thread will not keep a core busy: your Operating System will “park it” and free up one core for something else.

What threads are run on which core is the task of the Operating System: Go operates to run as many goroutines as possible on top of the available threads, instead of creating new ones which is a (relatively) expensive operation.

Generally you don’t care about cores, nor threads.

You do when your code performs CPU intensive operations (when it doesn’t do I/O or anything else with the external world): in this case you can change the “task affinity” of your Go process (in Linux, taskset) to fix your threads on one CPU. Probably you will also want to decrease the niceness of your process. Both these things might speed up your program, at the expense of making other programs running at the same time slower.


(Ignacio Gómez) #4

This is an interesting read about the Go scheduler and how goroutines relate to threads and cores: https://morsmachine.dk/go-scheduler.