Threads
Linux implementation of threads
Multiple threads execute within the same program in a shared memory address space.
In Linux, there are no concepts of threads, and all threads treated as standard processes. There is no special thread scheduling or data structures.
A thread is merely a process that shares resources with other processes. Every thread has a unique task_struct
.
Creation of threads
Threads are created the same way as normal tasks, except that for the clone()
system call, the resources to be shared are passed in as flags.
A normal fork()
calls clone this way
clone(SIGCHLD,0)
While a thread clone is called by
clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, 0)
This results in a behavior like a normal fork()
, except that the address, file system, file descriptors and signal handlers are shared.
The flags passed to clone()
tell it what resources the parent and child would share
Kernel Threads
Sometimes the kernel needs to perform some operations in the background. This is achieved via kernel threads, which are processes that exist solely in the kernel space.
The difference between kernel threads and normal processes is tat kernel threads do not have an address space. They only operate within kernel space and do not context switch into user space
Kernel threads can be seen by running ps -ef
A kernel thread can only be created by another kernel thread. The kernel forks all new kernel thread off the kthreadd
kernel process. The interface for spawning a new kernel thread is declared in <linux/kthread.h>
called kthread_create()
Kernel thread exits either when it called do_exit()
or if another part of the kernel calls kthread_stop()