Skip navigation

Mutex locks can be used to create blocking functions, a lot like the socket api’s recv() function.

Using Mutex objects
CreateMutex
WaitForSingleObject
ReleaseMutex


#include <stdio.h>
#include <conio.h>
#include <Windows.h>

// Super-short example that shows how to
// create a blocking function with mutex
// locks in MSVC++.

#define IsDown(x) (GetAsyncKeyState(x) & 0x8000)
HANDLE lock ;

DWORD WINAPI block( LPVOID data )
{
  puts( "Thread 2:  I have started.  I will check the lock.." ) ;
  WaitForSingleObject( lock, INFINITE ) ; // THE THREAD WILL BLOCK HERE
  // forever until the "lock" object is Released() by
  // the main thread
  puts( "Thread 2:  I AM FREE TO GO!!" ) ;

  return 0 ;
}

int main()
{
  // Get a lock on the lock variable
  lock = CreateMutexA(
    0,
    TRUE,  // When the mutex lock is created, start with it already "taken"
    "Main lock" // name for the lock
  ) ;

  puts( "Thread 1:  Starting new thread.." ) ;
  CreateThread( 0, 0, &block, 0, 0, 0 ) ;
  puts( "Thread 1:  Entering main loop.  Press the SPACEBAR to release the lock "
    "(to UNBLOCK) thread 2" ) ;
  while( 1 )
  {
    if( IsDown( VK_SPACE ) )
    {
      ReleaseMutex( lock ) ; // RELEASE OUR HANDLE ON THE
      // MUTEX LOCK, meaning the 'block()' function will
      // be free to continue execution
    }

    if( IsDown( VK_ESCAPE ) )
    {
      break ; // end the program
    }
  }

}


About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 41 other followers

%d bloggers like this: