[ LiB ] |
Now that you have experienced creating threads and waiting for them to finish, I want to show you how to have more control over your threads. For this example, I'm going to make a simple change to Demo 3.2, so that the PrintThread function will add a YieldThread() function call after every letter it prints:
void PrintThread( void* data ) { // convert the data passed in into a character. char c = (char)data; for( int i = 0; i < 10000; i++ ) { cout << c; cout.flush(); ThreadLib::YieldThread(); } }
Ta-da! That's it. The demo can be found on the CD in the directory /demos/chapter03/ demo03-02/ in the file demo03-02.cpp.
Now, what do you think will happen when you run this demo? Will the threads print out characters in alternating runs? Probably not. Whenever a character is printed, the function tells the operating system to yield and let another thread take a swing. Will this mean that we'll see nothing but an "abababab" pattern? Maybe not. Even though the threads may be queued alternately, that doesn't mean the operating system will run them in that order. We'll see what happens, though.
Figure 3.10 shows a screenshot of the program running on my Windows XP machine.
No matter how hard I tried, I couldn't get the program to display something other than repeating "ab"s. But even so, you're still not guaranteed to get that pattern, so just be aware of that fact.
[ LiB ] |