Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

c - What are trade offs for "busy wait" vs "sleep"?

This is an extension to my previous question

How does blocking mode in unix/linux sockets works?

What I gather from Internet now, all the process invoking blocking calls, are put to sleep until the scheduler finds the reasons to unblock it. The reasons can vary from buffer empty to buffer full to any other condition.

But then can this be an efficient way to real-time, let's say hard/firm real-time applications? As the process is not unblocked when the unblocking condition holds true, rather when the scheduler gives him his CPU slice, and the unblocking condition is both true.

As if u want a responsive solution, I don't think "spin locks" or "busy waits" are the right way to do it, CPU slices are wasted, and over-all the system shall get un-responsive or may poor-responsive.

Can somebody please clear these conflicting thoughts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Going to sleep until the scheduler wakes you is the normal/prefered thing to do.

Spinning (the alternative way to wait, without sleeping) is less usual and has the following effects:

  • Keeps the CPU busy, and prevents other threads from using the CPU (until/unless the spinning thread finishes its timeslice and is prempted)

  • Can stop spinning the very moment the thing which you're waiting for happens (because you're continuously checking for that event, and you don't need to take the time it takes to be woken up, because you're already awake)

  • Doesn't invoke the CPU istructions required to go to sleep and to wake up again

Spinning can be more efficient (less total CPU) than going to sleep, if the length of the delay is very short (e.g. if the delay is for only as long as it takes to execute 100 CPU instructions).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...