/********************************************** 作者:猪头流氓 时间:Tue Dec 26 16:45:30 2006 文件名:tt.c 描述:
gcc -o target tt.c -lpthread
gcc -o target tt.c -lpthread -DLOCK **********************************************/ #include #include
#ifdef LOCK pthread_mutex_t lm; #endif
void * func(void * avg); int count; int main() {
#ifdef LOCK pthread_mutex_init(&lm, NULL); #endif pthread_t pa,pb; pthread_create(&pa, NULL, &func, NULL); pthread_create(&pb, NULL, &func, NULL); pthread_join(pa, NULL); pthread_join(pb, NULL); return 0;
}
void * func(void *avg) { int i, val; for(i=0; i<20; i++) { #ifdef LOCK pthread_mutex_lock(&lm); #endif val=count; int rd=random(); sleep(rd%2); printf("%u:%d\n", pthread_self(), val+1); count++; #ifdef LOCK pthread_mutex_unlock(&lm); #endif }
} |