Demo 3.3Mutexes

[ LiB ]

Now I want to show you how to use mutexes to lock resources in a demo. Basically, I'm going to use the same format that was used in Demo 3.1 and 3.2 and just change the PrintThread() function again. This demo is located on the CD at /Demos/Chapter03/ Demo03-03/Demo03-03.cpp. The same compilation instructions apply.

This time, I want the threads to print 50 characters without being interrupted by the other printing thread. So, for every 50 characters, a global mutex will be locked to prevent the other thread from being called.

First, the mutex is defined:

 ThreadLib::Mutex m; 

Here's the new PrintThread() function:

 void PrintThread( void* data ) {     // convert the data passed in into a character.     char c = (char)data;     for( int i = 0; i < 200; i++ ) {         m.Lock();         for( int j = 0; j < 50; j++ ) {             cout << c;             cout.flush();         }         m.Unlock();     } } 

Now the printing loop is separated into two loops ; the outer loop prints 200 groups of 50 characters. Inside the outer loop, the mutex is locked, and then the 50 characters are printed. Once that is complete, the mutex is unlocked.

So what will you see when you run this program? Theoretically, you should see alternating blocks of 50 "a"s and then 50 "b"s. However, I'm again reminding you that this may not be the case. When the mutex is unlocked, it is entirely possible that execution may not switch to the other thread right away. In this case, the same thread might lock the same mutex and end up printing 100 characters in a row. While this is unlikely , it is still a possibility.

Figure 3.11 shows a screenshot of the demo in action.

Figure 3.11. This is a screenshot of the mutex Demo 3.3 .

graphic/03fig11.gif


As you can see, the characters were printed in blocks of 50, as predicted . So now you know how mutexes help you lock access to resources.

[ LiB ]


MUD Game Programming
MUD Game Programming (Premier Press Game Development)
ISBN: 1592000908
EAN: 2147483647
Year: 2003
Pages: 147
Authors: Ron Penton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net