This preview shows page 1. Sign up to view the full content.
Unformatted text preview: eads/maketimeout.c Figure 11.23: maketimeout: Builds a timeout structure for pthread cond timedwait. For a simple example of timeout waiting in a threaded program, suppose we want to write a beeping timebomb that waits at most 5 seconds for the user to hit the return key, printing out “BEEP” every second. If the user doesn’t hit the return key in time, then the program explodes by printing “BOOM!”. Otherwise, it prints “Whew!” and exits. Figure 11.24 shows a threaded timebomb that is based on the pthread cond timedwait function. The main timebomb thread locks the mutex and then creates a peer thread that calls getchar, which blocks the thread until the user hits the return key. When getchar returns, the peer thread signals the main thread that the user has hit the return key, and then terminates. Notice that since the main thread locked the mutex before creating the peer thread, the peer thread cannot acquire the mutex and signal the main thread until the main thread releases the mutex by calling pthread cond time...
View Full Document
- Spring '10
- The American