/* Copyright (C) 2008 Andreas Baumann This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "threads/threads.h" #include "threads/mutex.h" #include "port/unused.h" #include /* for EXIT_SUCCESS, EXIT_FAILURE */ #include /* for fprintf */ #define USE_MUTEX 1 #define NOF_LOOPS 10 #define NOF_THREADS 10 #if USE_MUTEX #define NOF_ITERATIONS 100000 #else #define NOF_ITERATIONS 1000000 #endif static int counter = 0; #if USE_MUTEX static wolf_mutex_t counter_mutex; #endif static WOLF_THREAD_RETURN_DECL thread_func( void *thread_data ) { int i; for( i = 0; i < NOF_ITERATIONS; i++ ) { #if USE_MUTEX wolf_mutex_lock( &counter_mutex ); #endif counter++; #if USE_MUTEX wolf_mutex_unlock( &counter_mutex ); #endif } WOLF_UNUSED( thread_data ); WOLF_THREAD_RETURN } int main( void ) { int i; int j; wolf_thread_t thread[NOF_THREADS]; wolf_error_t error; #if USE_MUTEX error = wolf_mutex_init( &counter_mutex ); if( error != WOLF_OK ) { fprintf( stderr, "Unable to create mutex: %d\n", error ); return EXIT_FAILURE; } #endif for( j = 0; j < NOF_LOOPS; j++ ) { for( i = 0; i < NOF_THREADS; i++ ) { error = wolf_thread_create( &thread[i], thread_func, NULL ); if( error != WOLF_OK ) { fprintf( stderr, "Unable to start thread %d: %d\n", i, error ); return EXIT_FAILURE; } printf( "Created thread %d\n", i ); fflush( stdout ); } for( i = 0; i < NOF_THREADS; i++ ) { error = wolf_thread_join( &thread[i] ); if( error != WOLF_OK ) { fprintf( stderr, "Unable to join thread %d: %d\n", i, error ); return EXIT_FAILURE; } printf( "Joined thread %d\n", i ); fflush( stdout ); } printf( "Value of counter: %d\n", counter ); if( counter != ( j + 1 ) * NOF_THREADS * NOF_ITERATIONS ) { fprintf( stderr, "Counter miscounted, is %d, must %d be!\n", counter, ( j + 1 ) * NOF_THREADS * NOF_ITERATIONS ); return EXIT_FAILURE; } } #if USE_MUTEX error = wolf_mutex_destroy( &counter_mutex ); if( error != WOLF_OK ) { fprintf( stderr, "Unable to destroy mutex: %d\n", error ); return EXIT_FAILURE; } #endif return EXIT_SUCCESS; }