Question on Deadlock

Eric Ivancich u-jeivan%sunset.utah.edu at utah-gr.UUCP
Thu Jun 23 12:20:54 AEST 1988


In article <2676 at utah-gr.UUCP> u-jeivan at ug.utah.edu.UUCP (I) write:
>I have a question concerning deadlock.  I fear that everyone knows
>this but me, but I have to learn somehow.  I understand the basic
>concept of deadlock--two (in a simple case) entities, both waiting for
>an action of the other.  However, I do not understand why the attached
>code produces deadlock.
>...

As promised, I will summarize.  First of all, thanks to Dieter,
Greg Limes, Tim Olson, and John P. Nelson for responding.

The problem isn't deadlock at all, but a buffering problem.

John P. Nelson writes:
| You are getting bitten by stdio buffering.  This is fairly well-known,
! but is a common misunderstanding with novices.
| 
! The workaround is to put the line "fflush(stdout)" just before Segment_B.
| Then everything functions the way you expected.  Your logic is flawless,
! but there was a factor that you were not taking into account.
| 
! The first time a stdout is written to, the code checks to see what kind
| of low-level descriptor is attached to it:  If it is a terminal, then
! "stdout" is either unbuffered or line-buffered (depending on the version
| of unix you are running).  If the file descriptor is attached to a
! pipe or file, then the stdio descriptor is "fully buffered":  I.e. no
| output actually occurs until the buffer (BUFSIZ) is full, or until
! an explicit flush() is performed.
| 
! This behavior almost always does the "right thing": interactive tasks
| get immediate response, and files and pipes get the most efficient
! buffering.  The problem is because you are using a pipe in an interactive
| manner (which is quite unusual!), the stdio defaults break down.
! 
| Besides calling "flush" explicitly each time you expect to "turn-around"
! to a read operation, you can change the buffering characteristics of
| the stdout explicitly using "setbuf(stdout, NULL)", (or preferably
! "setlinebuf(stdout)", if your library supports it).  Setbuf(...,NULL)
| causes a "FILE *" to be completely unbuffered:  Every stdio write operation
! will result in a low-level "write()" call.  Setlinebuf is similar, except
| that the buffer is only flushed on newlines, instead of on every operation.

Now I know.

Eric

||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
They pelted us with rocks and garbage.      - Late Night with David Letterman

INFO: Eric Ivancich : University of Utah
UUCP: {ihnp4, hplabs, decvax, arizona}!utah-ug!u-jeivan
ARPA: u-jeivan at ug.utah.edu
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||



More information about the Comp.unix.questions mailing list