FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Database
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
January 01, 2003

Multithreaded Programming with the Command Pattern

(Page 4 of 6)
Multithreaded Programming with the Command Pattern

Listing 3 This app reads messages from a queue by using a thread pool



#include <iostream>
#include <string>
#include <vector>

#include <windows.h>

HANDLE condition;
HANDLE mutex;

std::vector < std::string > queue;

void thread_entry ()
{
  for ( ;; )
  {
    WaitForSingleObject ( mutex, INFINITE );
    if ( queue.empty () )
    {

	  ReleaseMutex ( mutex );
      std::cout << "thread going to sleep" << std::endl;
      WaitForSingleObject ( condition, INFINITE );

	  WaitForSingleObject ( mutex, INFINITE );
      std::cout << "thread awake" << std::endl;
    }

    if ( queue.empty () )
    {
      std::cout << "work queue is empty" << std::endl;
      ReleaseMutex ( mutex );
      continue;
    }

    std::string message = queue.back ();
    queue.pop_back ();
    ReleaseMutex ( mutex );

    std::cout << message << std::endl;
    Sleep ( 1 );
  }
}

int main ()
{
  HANDLE threads[ 3 ];
  std::string messages[ 10 ] = { "hello", "goodbye", "test", "check",
                                 "one", "two", "james", "way-way",
                                 "here", "there" };


  mutex = CreateMutex ( NULL, FALSE, NULL );

  condition = CreateEvent ( NULL, FALSE, FALSE, NULL );


  for ( int i = 3; i > 0; --i )
  {
    threads[ i - 1 ] = CreateThread ( NULL, 0,
                              ( LPTHREAD_START_ROUTINE ) thread_entry,
		         NULL, 0, NULL );
  }

  for ( int index = 10; index > 0; --index )
  {
    WaitForSingleObject ( mutex, INFINITE );
    queue.push_back ( messages[ index - 1 ] ); 
    SetEvent ( condition );
    ReleaseMutex ( mutex );
  }

  WaitForSingleObject ( threads[ 0 ], INFINITE );

  return ( 0 );
}

Previous Page | 1 | 2 | 3 | 4 | 5 | 6 Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK