/* * Get max integer value from an array of integers * * Divide and conquer strategy is used. Array is divided into multiple pieces to that multiple threads can run parellely. */ #include #include #define THREAD_COUNT 3 #define DATA_SIZE_IN_EACH_THREAD 5 pthread_mutex_t mutex; unsigned max_value; /* * Start routine for the thread. * This is thread's starting point. Like main() for process. */ void *thread_start_routine( void *int_array ) { unsigned i, thread_max_value=0; unsigned *data = (unsigned*)int_array; printf("Start routine of thread %p called.\n", pthread_self()); /* Detect max int value */ for(i=0; ithread_max_value) thread_max_value = data[i]; } /* Lock, update result in shared global variable, unlock */ pthread_mutex_lock(&mutex); if(thread_max_value>max_value) max_value = thread_max_value; pthread_mutex_unlock(&mutex); return 0; /* Thread execution completed */ } /* * Main Function */ int main(int argc, char *argv[]) { unsigned data_array[THREAD_COUNT*DATA_SIZE_IN_EACH_THREAD] = { 1,2,3,4,5,6,7,8,7,6,5,4,3,2,1 }; int retval, i; pthread_t childThread[THREAD_COUNT] = {0}; /* Initialize mutex for synchronized modification of shared global var 'max_value' */ retval = pthread_mutex_init(&mutex, NULL); /* Create Threads with default behavior. */ for(i=0; i