CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 5 of 7 · 2 min read

Linux and clone

In plain words: Linux has one kernel record type for both processes and threads, called a task (task_struct, Level 1, page 2). A thread is simply a task that shares its address space and some other resources with another task. The system call that makes this choice is clone. It works like fork, but its flags say what the new task shares with the creator:

Flag Meaning
CLONE_VM Share the address space
CLONE_FILES Share the table of open file descriptors
CLONE_FS Share the current directory and root directory
CLONE_SIGHAND Share the signal handlers
CLONE_THREAD Put the new task in the same thread group, so it has the same process ID

fork is a call to clone with no sharing flags. pthread_create is a call to clone with all of the flags above and a new stack. A run of strace -f on a program that creates one thread showed it:

clone3({flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|
        CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, ...}) = 30359

The system call here is clone3, the newer version of clone that modern libraries use. The return value 30359 is the thread ID of the new task. This explains what page 1 observed: all threads have the same process ID (the thread group's ID) and different thread IDs. The user-space library for this on Linux is the Native POSIX Thread Library (NPTL), part of the C library.

The result is the one-to-one model with a nice property: the kernel needs no special thread code. Every thread is a task, and the scheduler treats all tasks alike, whether or not they share memory.

clone

clone is the Linux system call that creates a new task and lets the caller choose, by flags, which resources it shares with the new task, such as the address space, the open files and the signal handlers. fork uses it with no sharing, and pthread_create uses it with sharing.

Example: clone with CLONE_VM makes a task that uses the same memory as its creator, which is what a thread is.

Check yourself: 1. What does CLONE_VM share? 2. Which call is fork in terms of clone? 3. Why do all threads of a process show the same process ID?