Linux 用户态线程和内核态线程

本文详细介绍了Linux中用户态线程和内核态线程的区别、优缺点,包括用户态线程的轻量级进程(LWP)绑定模型,并探讨了内核线程的创建、管理及其应用场景。用户态线程快速创建,但面临阻塞问题;内核线程由操作系统管理,支持多处理器调度,但创建较慢。
摘要由CSDN通过智能技术生成

一、用户态线程和内核态线程区别

首先,线程是最基本的执行和调度单元。

线程所运行的代码分为两部分:用户代码、内核代码。其中用户代码就是用户自己开发编译的,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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

denglin12315

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值