#include #include #include #define NUM 100 void *countupdown( void* ptr ); long count[NUM]; int max = NUM; long limit =1000000L; int main(int argc, char* argv[]) { pthread_t thread1, thread2, thread3, thread4; int iret1, iret2, iret3, iret4; int i, j; char* option; char* arg; /* 引数の処理 */ for ( i = 1 ; i < (argc-1) ; i+=2 ) { option = argv[i]; arg = argv[i+1]; if ( strcmp(option, "-max") == 0 ) { max = atoi(arg); if ( max > NUM ) { fprintf(stderr, "max is too large\n"); exit(1); } } else if ( strcmp(option, "-limit") == 0 ) { limit = atol(arg); } else { fprintf(stderr, "Unknown option: %s\n", option); exit(2); } } printf("max=%d\n", max); printf("limit=%d\n", limit); /* スレッドの生成 */ iret1 = pthread_create( &thread1, NULL, countupdown, (void*) "thread1"); iret2 = pthread_create( &thread2, NULL, countupdown, (void*) "thread2"); iret3 = pthread_create( &thread3, NULL, countupdown, (void*) "thread3"); iret4 = pthread_create( &thread4, NULL, countupdown, (void*) "thread4"); /* 全てのスレッドの終了待ち */ pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); /* 結果の表示 */ for ( j=0 ; j < max ; j++ ) { printf("count[%d]=%ld\n", j, count[j]); } exit(0); } void *countupdown( void *name ) { char* string = (char*)name; long i = 0; long j = 0; for ( i=0 ; i < limit ; i++ ){ for ( j=0 ; j < max ; j++ ) { count[j] = count[j] + 2; } for ( j=0 ; j < max ; j++ ) { count[j] = count[j] - 2; } } }