Process 什么';阻塞和繁忙等待之间有什么不同?
我知道忙着等待的意义。这是一个类似这样的死亡循环:Process 什么';阻塞和繁忙等待之间有什么不同?,process,operating-system,pthreads,blocked-threads,Process,Operating System,Pthreads,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(); }
//main thread
while (true) {
msg = msgQueue.next();
msg.runnable.run();
}
//....msg queue
public Message next() {
while (true) {
if (!queue.isEmpty()) {
return queue.dequeue();
}
}
}
100: if (data_available()) {
101: return;
102: } else {
103: jump_to_scheduler();
104: }
因此,方法“next()”看起来像是阻塞的,实际上它一直在运行。
这被称为“忙碌的等待”的书
什么是“进程受阻”?它的实现细节如何?
也是死亡循环吗?还是其他一些?比如信号机制
例如:
xxx类| grep“abc”
进程“cat”读取一个文件并输出它们
处理“grep”,等待“cat”的输入
所以在“cat”输出数据之前,“grep”应该被阻塞,等待输入并继续。
关于这个“阻塞”的详细信息,死亡循环一直在读取输入流?或者真的停止运行,等待信号唤醒它运行?区别基本上在于进程发生了什么: 1。忙着等待 一个忙着等待的进程基本上是连续运行的,它会问“我们到了吗?我们到了吗?现在怎么样,我们到了吗?”这会消耗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();
}
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
更新
可等待对象可以在操作系统级别以不同的方式实现,但通常它可能是硬件计时器、中断和通过客户端代码注册到操作系统的可等待对象列表的组合。当中断发生时,操作系统的中断处理程序将被调用,该处理程序将依次扫描与该事件相关联的任何可等待对象,并调用特定的回调,该回调最终将向可等待对象发送信号(将其置于信号状态)。这过于简化了,但如果您想了解更多信息,可以阅读中断和硬件计时器。当您说“进程被阻塞”时,实际上是指“线程被阻塞”,因为这些是获得CPU时间的唯一可调度实体。当线程忙于等待时,它会在循环中浪费CPU时间。当线程被阻塞时,系统调用中的内核代码会发现数据或锁不立即可用,因此它会将线程标记为正在等待。然后,它跳转到调度程序,调度程序选择另一个准备执行的线程。阻塞系统调用中的此类代码可能如下所示:
//main thread
while (true) {
msg = msgQueue.next();
msg.runnable.run();
}
//....msg queue
public Message next() {
while (true) {
if (!queue.isEmpty()) {
return queue.dequeue();
}
}
}
100: if (data_available()) {
101: return;
102: } else {
103: jump_to_scheduler();
104: }
稍后,线程被重新调度并在第100行重新启动,但它立即到达else分支并再次脱离CPU。当数据可用时,系统调用最终返回
不要一字不差地说,我是根据我对操作系统的了解来猜测的,但你应该明白这一点。嗯。。。操作系统如何做到这一点?大家好,现在,我知道了区别:D,忙等待是一个循环,cpu将一直执行它,块是一种内核/操作系统控制,它不会浪费cpu资源。