阻塞原理 tsleep 和 wake 系统调用

本文深入探讨了Linux内核中通过调用tsleep和wakeup函数实现的资源等待与唤醒机制。详细解释了当进程在内核中执行时,因缺少资源而无法继续运行时如何使用tsleep函数进入等待状态,以及当资源可用或事件发生时,内核通过wakeup函数唤醒等待的进程。特别强调了当多个进程共享同一等待通道时,资源分配和进程调度的逻辑,以及这一机制在高效处理网络连接等场景的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘选: TcpV2 15.10节

tsleep and wakeup Functions

阻塞:

  When a process executing within the kernel cannot proceed because a kernel
resource is unavailable, it waits for the resource by calling tsleep, which has
the following prototype:  

    int tsleep (caddr_t chan, int pri, char *mesg, int timeo);

  The first argument to tsleep, chan, is called the wait channel. It identifies the
particular resource or event such as an incoming network connection, for
which the process is waiting. Many processes can be sleeping on a single wait
channel.  pri:唤醒时被调度的优先级.

  联系:ps -l 显示的WCHAN列: 进程正在睡眠的内核函数名称;
该函数的名称是从/root/system.map文件中获得的。也就是mesg参数

mesg is a string identifying the call to tsleep and is included
in debugging messages and in ps output.

唤醒:

  When the resource becomes available or when the event occurs, the
kernel calls wakeup with the wait channel as the single argument. The
prototype for wakeup is:
    void wakeup (caddr_t chan);
  All processes waiting for the channel are awakened and set to the run state.
The kernel arranges for tsleep to return when each of the processes resumes
execution.

 

注意:

  当多个process wait在同一个channel上时,一但唤醒,这些process都被放入执行队列。
但是各个precess消耗到来的资源之前必须判断一下资源是否可用。因为该资源可能已经被同时唤醒
的另一process取到。If the resource is not available, the process calls tsleep once again.

举例:

  One use of multiple processes sleeping on the same wait channel is to have
multiple server processes reading from a UDP socket. Each server calls
recvfrom and, as long as no data is available, the calls block in tsleep. When
a datagram arrives on the socket, the socket layer calls wakeup and each
server is placed on the run queue. The first server to run receives the
datagram while the others call tsleep again. In this way, incoming datagrams
are distributed to multiple servers without the cost of starting a new process
for each datagram. This technique can also be used to process incoming
connection requests in TCP by having multiple processes call accept on the
same socket. This technique is described in [Comer and Stevens 1993].

 

 

转载于:https://www.cnblogs.com/tangr206/archive/2013/05/16/3081696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值