linux-kernel

Is the main thread of a userspace process a kernel thread running in kernel space?


I thought I understood kernel threads vs user threads, but there's something I can't figure out that suggests I'm missing something.

I thought these were facts:

  1. when the kernel creates a process it also creates the process's main thread
  2. the kernel can only create kernel threads (knows nothing about user threads)
  3. kernel threads can only run in kernel space
  4. when the process runs in user space, its main thread also runs in userspace

But that seems contradictory. A process running in user mode has a main thread running in kernel space? That doesn't seem right.

I think it's probably 3 that's wrong, but I see conflicting information online and don't have an authoritative source: this says that kernel threads can run in user space, and this says they're only in kernel space.


Solution

  • In Linux, Userspace threads and kernel threads are two very different things. The first answer you link is addressing the general concept of "kernel thread" and does not refer specifically to Linux. The article you link talks specifically about Linux.

    In Linux:

    Now, let's address your points one by one:

    1. when the kernel creates a process it also creates the process's main thread

    When the kernel creates a userspace "process", it is creating a single task, i.e. a single userspace thread. That thread is the one and only thread. It is referred to as the "main thread" of a process. No kernel thread is created. After this, other threads can be created by the main thread via clone with the special flag CLONE_THREAD and they are all considered part of the same "process". A new main thread can also be created to have a new, separate process via fork.

    1. the kernel can only create kernel threads (knows nothing about user threads)

    This is not true. In fact, userspace needs to invoke kernel code via syscalls (fork, clone) to create new threads. Only the kernel knows how to do it. In special circumstances, the kernel can even create new standalone userspace tasks without explicit request by the user.

    1. kernel threads can only run in kernel space

    Correct.

    1. when the process runs in user space, its main thread also runs in userspace

    We need to define "process" correctly here. A "process" is a group of tasks (userspace threads), one of which is the main thread. Each task runs on its own, and can run either in user or kernel space at any given time. The code of the task itself always runs in userspace, but when the task invokes a system call, it transitions into kernel space and starts executing kernel code.