A process can do more than one thing at a time by using threads. A thread is a single path of execution. Every process has at least one.
What is shared
Threads in the same process share:
- the memory address space
- open file descriptors
- the working directory and signal handlers
Each thread has its own stack, registers and scheduling state. The kernel schedules threads individually, so a program with several can use several CPUs at once.
Sharing memory makes communication cheap, but it also means two threads can change the same data at once. Programs need locks to prevent that. A crash such as a segmentation fault normally takes down the whole process, every thread included.
IDs
Each thread has its own thread ID, shown as LWP (lightweight process) or TID. All threads of a process share one PID, which equals the ID of the first thread.
Seeing threads
$ ps -T -p 1893
PID SPID TTY TIME CMD
1893 1893 ? 00:02:10 firefox
1893 1901 ? 00:00:03 gmain
1893 1902 ? 00:00:11 gdbusHere SPID is the thread ID. ps -eLf lists every thread on the system, with LWP and NLWP (number of threads) columns:
$ ps -o pid,nlwp,comm -p 1893
PID NLWP COMMAND
1893 74 firefoxIn top, press H or start it with top -H to show threads as separate rows. This helps find the one thread that is eating a CPU.
The kernel also exposes them under /proc, one directory per thread:
$ ls /proc/1893/task
1893 1901 1902 ...Threads or processes?
Some programs use many processes instead. Separate processes are better isolated, since one crashing need not harm the others, but sharing data takes more work. Many servers and browsers mix both.
Under the hood, Linux creates both with the clone system call. The difference lies in how much the new task shares with its creator.
Try it
Run ps -eo pid,nlwp,comm --sort=-nlwp | head to find the most threaded processes on your machine. Choose one and list its threads with ps -T -p PID. Your shell likely has just one. Try this in the processes and cron lab.
Check your understanding
Processes and threads
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.