Blocked和Busy Waiting之间有什么不同?

Kro*_*oss 8 operating-system pthreads process blocked-threads

我知道忙碌等待的实现.这是一个像这样的死循环:

//main thread
while (true) {
    msg = msgQueue.next();
    msg.runnable.run();
}

//....msg queue
public Message next() {
    while (true) {
        if (!queue.isEmpty()) {
            return queue.dequeue();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,方法"next()"看起来就像被阻止了,实际上它一直在运行.这被称为"忙着等待".

什么是"过程受阻"?它的实施细节怎么样?还是一个死循环?或其他一些人?像信号机制?

例如:cat xxx | grep"abc"

进程"cat"读取文件并输出它们.

处理"grep"等待"cat"的输入.

所以在"cat"输出数据之前,应该阻止"grep",等待输入并继续.关于这个"被阻止"的详细信息,死循环一直读取输入流?或者真的停止运行,等待一个信号唤醒它运行?

Mik*_*scu 12

差异基本上在于流程发生的变化:

忙碌的等待

一个忙着等待的过程基本上在不停地运行,问"我们还在吗?我们还在吗?现在怎么样,我们还在吗?" 这个问题消耗了100%的CPU周期:

bool are_we_there = false;
while(!are_we_there)
{
   // ask if we're there (without blocking)
    are_we_there = ask_if_we_are_there();
}
Run Code Online (Sandbox Code Playgroud)

2.被阻止(或阻止)的进程

被阻止的进程将被操作系统挂起,并在其正在等待的数据可用时自动通知.没有操作系统的帮助,这是不可能完成的.

例如,一个等待长时间运行的I/O操作或等待计时器到期的进程:

// use a system call to create a waitable timer
var timer = CreateWaitableTime()

// use another system call that waits on a waitable object
WaitFor(timer);  // this will block the current thread until the timer is signaled

// .. some time in the future, the timer might expire and it's object will be signaled
//    causing the WaitFor(timer) call to resume operation
Run Code Online (Sandbox Code Playgroud)

UPDATE

可以在操作系统级别以不同方式实现可等对象,但是通常它可能是硬件定时器,中断和通过客户端代码向操作系统注册的可等待对象列表的组合.当发生中断时,将调用操作系统的中断处理程序,该处理程序将依次扫描与该事件关联的任何可等待对象,并调用某些回调,这最终将发出可等待对象的信号(将它们置于信号状态).这是一种过度简化,但如果您想了解更多信息,可以阅读中断和硬件定时器.