一、用户态线程和内核态线程区别
首先,线程是最基本的执行和调度单元。
线程所运行的代码分为两部分:用户代码、内核代码。其中用户代码就是用户自己开发编译的,exe里面的就是用户代码。内核代码是编译进OS内核的,不需要应用程序自己开发,通过syscall就能调用内核代码,相当于一个用户函数调用了内核函数。
系统中运行的各个应用程序,它们的用户代码各不相同,但是内核代码都是一样的。线程运行过程中,会在用户状态和内核状态之间来回切换。
但是,存在一些特殊的线程,它们没有用户代码,一直工作在内核状态。入口点main也是放在内核代码中的,这样的线程就是内核线程。既然身处内核代码,因此内核线程必须与OS内核一起编译,或者以内核模块的形式动态添加到内核地址空间中。
那些既有用户代码,又可以通过syscall调用允许的内核功能(非必须)的线程,就是用户线程。如果不特别说明,人们提到线程,通常指的就是用户线程。虽然名字叫做用户线程,但也可以运行内核代码,不过只能使用,不能开发内核下的函数。
用户代码如果想调用内核函数,必须通过syscall,而syscall总数是有限的,安全检查也比较严格。但是一个内核函数调用其他的内核函数就没有限制了。内核线程的入口点放在内核里,因此可以使用syscall之外的内核功能,比单纯的用户代码执行系统调用能实现更多的功能。
二、用户态线程和内核态线程的优缺点
The two main types of threads are user-level threads and kernel-level threads. A diagram that demonstrates these is as follows:
User - Level Threads
The user-level threads are implemented by users and the kernel is not aware of the existence of these threads. It handles them as if they were single-threaded processes. User-level threads are small and much faster than kernel level threads. They are represented by a program counter(PC), stack, registers and a small process control block. Also, there is no kernel involvement in synchronization for user-level threads.
Advantages of User-Level Threads
Some of the advantages of user-level threads are as follows −
- User-level threads are easier and faster to create than kernel-level threads. They can also be more easily managed.
- User-level threads can be run on any operating system.
- There are no kernel mode privileges required for thread switching in user-level threads.
Disadvantages of User-Level Threads
Some of the disadvantages of user-level threads are as follows −
- Multithreaded applications in user-level threads cannot use multiprocessing to their advantage.