---
# System prepended metadata

title: Thread
tags: [LinuxKernel]

---

# Thread
- The Linux kernel utilizes the `task_struct` structure, which can be viewed [here](https://web.git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/sched.h) to manage threads.
    ```c=
    struct task_struct {
        ...
        pid_t pid;
        pid_t tgid;
        ...
    }
    ```
- Every *thread* in a *Thread Group* maps to a task structure in the kernel.
- The `pid` variable correspond to a thread ID, and `tgid`, meaning *Thread Group ID* corresponds to a process ID.
    | User layer | System call | Variable mapped in Kernel <br/> `task_struct` structure |
    | :--------: | :--------: | :--------: |
    | Thread ID | pid_t gettid(void) | pid_t pid |
    | Process ID | pid_t getpid(void) | pid_t tgid |
- Use the following command to retrieve the information about threads, where `LWP` represents the thread ID and `NLWP` indicates the *Number of LWP*s. Additionally, the process *systemd+* is multi-thread, with four threads having thread IDs 1195, 1358, 1359,and 1360.
    ```shell=
    $ ps -eLF -L
    F S UID          PID    PPID     LWP  C NLWP PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
    4 S syslog      1295       1    1295  0    4  80   0 - 55647 -      14:43 ?        00:00:00 /usr/sbin/rsyslogd -n -iNONE
    1 S syslog      1295       1    1358  0    4  80   0 - 55647 -      14:43 ?        00:00:00 /usr/sbin/rsyslogd -n -iNONE
    1 S syslog      1295       1    1359  0    4  80   0 - 55647 -      14:43 ?        00:00:00 /usr/sbin/rsyslogd -n -iNONE
    1 S syslog      1295       1    1360  0    4  80   0 - 55647 -      14:43 ?        00:00:00 /usr/sbin/rsyslogd -n -iNONE
    ```
- Use the following command to search for all threads of a given process ID. `procfs` creates a subdirectory for each thread in the `/proc/PID/task` path.
    ```shell=
    $ ll /proc/1295/task
    total 0
    dr-xr-xr-x 6 syslog syslog 0  3月 20 22:44 ./
    dr-xr-xr-x 9 syslog syslog 0  3月 20 14:43 ../
    dr-xr-xr-x 7 syslog syslog 0  3月 20 22:44 1295/
    dr-xr-xr-x 7 syslog syslog 0  3月 20 22:44 1358/
    dr-xr-xr-x 7 syslog syslog 0  3月 20 22:44 1359/
    dr-xr-xr-x 7 syslog syslog 0  3月 20 22:44 1360/
    ```
# Reference
- [index : kernel/git/torvalds/linux.git](https://web.git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/sched.h)
- [gettid(2) — Linux manual page](https://man7.org/linux/man-pages/man2/gettid.2.html)