#include #include #include typedef struct { int i; int loops; } shared; //shared s = { 0, 1000000 }; void *worker( void *arg ) { shared *s = (shared*)arg; int i = 0; for( i=0; i < s->loops; ++i ) { //__sync_fetch_and_add( &s->i, s->i + 1 ); __sync_fetch_and_add( &s->i, 1 ); } return; } void main( int argc, char **argv ) { int i = 0, nThreads = 4; clock_t start, finish; double elapsed; pthread_t threads[32]; shared s = { 0, 1000000 };; if( argc > 1 ) nThreads = atoi( argv[1] ); if( argc > 2 ) s.loops = atoi( argv[2] ); printf( "threads:%d loops:%d\n", nThreads, s.loops ); start = clock(); for( i=0; i < nThreads; ++i ) pthread_create( &threads[ i ], NULL, &worker, &s ); for( i=0; i < nThreads; ++i ) pthread_join( threads[ i ], NULL ); finish = clock(); elapsed = (double)(finish - start) / CLOCKS_PER_SEC; printf( "count: %u time:%.6f\n", s.i, elapsed ); }