void destroy_threadpool(threadpool destroyme) { _threadpool *pool = (_threadpool *) destroyme; void* nothing; int i = 0; free(pool->threads); mypthread_mutex_destroy(&(pool->mutex)); mypthread_cond_destroy(&(pool->cond)); mypthread_exit(NULL); return; }
int main( int argc, char **argv ) { int i, *pList = 0, nListSize = LISTSIZE; mypthread_t *threads, thrcheck; mypthread_mutex_t *mutexes; struct pthrarg *pthrargs, pthrargcheck; if( argc == 2 ) nListSize = atoi( argv[1] ); nListSize = nListSize > 0 ? nListSize : LISTSIZE; // Creating the List of numbers printf( "Number of elements: %d\n", nListSize ); pList = (int *) malloc( sizeof( int ) * nListSize ); for( i = 0; i < nListSize; i++ ) pList[i] = random( ) % (nListSize<<1); // random list // pList[i] = nListSize-i; // decreasing list (easier to debug) printf( "[BEFORE] The list is NOT sorted:\n" ); printList( pList, nListSize ); threads = (mypthread_t *) malloc( sizeof(mypthread_t) * (nListSize-1) ); mutexes = (mypthread_mutex_t *)malloc( sizeof(mypthread_mutex_t) * nListSize ); pthrargs = (struct pthrarg *)malloc( sizeof(struct pthrarg) * (nListSize-1) ); mypthread_mutex_init( &mutexes[0], 0 ); for( i = 0; i < nListSize-1; i++ ) { mypthread_mutex_init( &mutexes[i+1], 0 ); pthrargs[i].num = &pList[i]; pthrargs[i].mtx = &mutexes[i]; pthrargs[i].size = nListSize; if( mypthread_create( &threads[i], 0, &fnsort, &pthrargs[i] ) != 0 ) { printf( "[FATAL] Could not create thread: %d\n", i ); exit( 1 ); } } pthrargcheck.num = pList; pthrargcheck.mtx = mutexes; pthrargcheck.size = nListSize; if( mypthread_create( &thrcheck, 0, &fncheck, &pthrargcheck ) != 0 ) { printf( "[FATAL] Could not create thread: fncheck\n" ); exit( 1 ); } /////////// // Waiting the threads to complete the sorting ////////// printf( "waiting...\n" ); for( i = 0; i < nListSize-1; i++ ) mypthread_join( threads[i], 0 ); mypthread_join( thrcheck, 0 ); for( i = 0; i < nListSize; i++ ) mypthread_mutex_destroy( &mutexes[i] ); printf( "[AFTER] The list is sorted:\n" ); printList( pList, nListSize ); // Cleaning free( pthrargs ); free( mutexes ); free( threads ); free( pList ); return 0; }