# Linux Kernel Module Cheat

### 17.9. kthread

Kernel threads are managed exactly like userland threads; they also have a backing `task_struct`, and are scheduled with the same mechanism:

    insmod kthread.ko

Source: kernel_modules/kthread.c

Outcome: dmesg counts from `0` to `9` once every second infinitely many times:

    0
    1
    2
    ...
    8
    9
    0
    1
    2
    ...

The count stops when we `rmmod`:

    rmmod kthread

The sleep is done with `usleep_range`, see: Section 17.9.2, “sleep”.

Bibliography:

- https://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel

- https://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit

- kthreads

- sleep

- Workqueues

- schedule

- Wait queues