Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux - run process on several cores

I have a misunderstanding about how cores, process and threads works:

  • Process has number of threads.
  • All those threads share same memory section
  • Core has it's own cache and memory address space.

So, when I'm running a process (which contains several threads) on Linux OS, and check the "top -H" command, I can see that the threads are distributed on multiple cores.

So How can it works ? (Threads of same process, which share same process address space, run on different cores ?) ?

What I miss here ?

Thanks

like image 499
user3668129 Avatar asked Aug 19 '14 18:08

user3668129


2 Answers

The Linux kernel scheduler is scheduling tasks. See this answer to a nearly identical question which explains what tasks are.

A task may run (at a given moment) on some single core. The scheduler may move tasks from one core to another (but rarely do so, since it takes time to warm up a core and its L1 cache).

A multi-threaded process usually have several tasks (one per thread) which usually can run on several cores.

You probably should avoid having a big lot of threads per process. I would recommend at most a dozen threads, especially if several of them are runnable (but details vary with hardware and system)

Read also about processor affinity

like image 76
Basile Starynkevitch Avatar answered Oct 22 '22 04:10

Basile Starynkevitch


Every time that the operating system switches a CPU to another thread, it sets all the registers on the CPU for that thread. This includes the current stack, the memory access permissions, all of that.

So when two threads of the same process run on two different CPU cores, each of those cores is set to access that process memory.

When the operating system decides that one of the threads has used too much CPU time, it suspends the thread and copies all the CPU registers into memory. It then loads another thread into the CPU core.

like image 1
Zan Lynx Avatar answered Oct 22 '22 03:10

Zan Lynx