/* File: thread_main.cpp Copyright 2009 Chris Tonkinson (cmtonkinson@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ /** * @file thread_main.cpp * @author Chris Tonkinson (cmtonkinson@gmail.com) * @date April 2009 * @brief Test driver for the Thread, Mutex, RWMutex, and ThreadException classes. */ #include #include #include #include "thread.h" #define NUMBER_OF_THREADS 5 void* speak( void* ptr ); int main( int argc, char* argv[], char* envp[] ) { try { std::vector threads; unsigned short* usp = NULL; printf( "Creating threads...\n" ); for ( unsigned short u=0; u < NUMBER_OF_THREADS; ++u ) { usp = new unsigned short( u ); threads.push_back( new Thread( speak, (void*)usp ) ); } printf( "Active threads...\n" ); for ( std::vector::iterator it = threads.begin(); it != threads.end(); ++it ) { printf( "\tActive thread with ID %lu\n", (*it)->ID() ); } printf( "Are the threads done yet?...\n" ); for ( std::vector::iterator it = threads.begin(); it != threads.end(); ++it ) { if ( (*it)->complete() ) { printf( "\tThread %lu is complete.\n", (*it)->ID() ); } else { printf( "\tThread %lu is is not yet complete.\n", (*it)->ID() ); } } printf( "Waiting for threads to terminate...\n" ); for ( std::vector::iterator it = threads.begin(); it != threads.end(); ++it ) { (*it)->join(); printf( "\tReturn status of thread %lu is %d.\n", (*it)->ID(), *((int*)(*it)->returnValue()) ); } for ( std::vector::iterator it = threads.begin(); threads.size(); it = threads.begin() ) { printf( "\tDeleting thread %lu.\n", (*it)->ID() ); delete (unsigned short*)(*it)->argument(); delete (int*)(*it)->returnValue(); delete *it; threads.erase( it ); } } catch ( ThreadException te ) { fprintf( stderr, "Caught: %s\n", te.message().c_str() ); return EXIT_FAILURE; } return EXIT_SUCCESS; } void* speak( void* ptr ) { Thread* thread = (Thread*)ptr; unsigned short us = *((unsigned short*)thread->argument()); usleep( 200 ); printf( "Howdy from thread %lu with argument %u!\n", thread->ID(), us ); thread->returnValue( new int( rand() ) ); thread->complete( true ); return NULL; }