#include #include #define MAXNPROC 64 #define P 2 bin(int n) { if(n==0) return 1; else { int t1 = bin(n-1); int t2 = bin(n-1); return t1+t2; } } int systhr_create(void * (*start_func)(void *), void *arg){ int status = 0; pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); status = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); if(status == 0) status = pthread_create(&tid, &attr, start_func, arg); if(status != 0) status = pthread_create(&tid, 0, start_func, arg); return status; } pthread_mutex_t acc_lk = PTHREAD_MUTEX_INITIALIZER; int acc_r = 0; struct bin_task { int k; }; pthread_mutex_t taskbuf_lk = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t taskbuf_cond_get = PTHREAD_COND_INITIALIZER; pthread_cond_t taskbuf_cond_put = PTHREAD_COND_INITIALIZER; int taskbuf_filled = 0; int taskbuf_request = 0; struct bin_task taskbuf_data; void gen_task(int k) { pthread_mutex_lock(&taskbuf_lk); while(taskbuf_filled || taskbuf_request == 0) pthread_cond_wait(&taskbuf_cond_put, &taskbuf_lk); taskbuf_data.k = k; taskbuf_filled = 1; taskbuf_request--; pthread_cond_broadcast(&taskbuf_cond_get); pthread_mutex_unlock(&taskbuf_lk); } void get_task(struct bin_task *tk) { pthread_mutex_lock(&taskbuf_lk); taskbuf_request++; pthread_cond_broadcast(&taskbuf_cond_put); while(!taskbuf_filled) pthread_cond_wait(&taskbuf_cond_get, &taskbuf_lk); tk->k = taskbuf_data.k; taskbuf_filled = 0; pthread_cond_broadcast(&taskbuf_cond_put); pthread_mutex_unlock(&taskbuf_lk); } void set_result(int r) { pthread_mutex_lock(&acc_lk); acc_r += r; pthread_mutex_unlock(&acc_lk); } struct warg { int myid; }; void *fworker(void *arg) { struct warg *x = arg; int myid = x->myid; while(1) { struct bin_task tk; int rr; get_task(&tk); /* printf("get %d\n", tk.k); */ rr = bin(tk.k); set_result(rr); } } bin_m(int n, int k) { if (k < n*3/4) { /* printf("gen %d\n", k); */ gen_task(k); } else { bin_m(n, k-1); bin_m(n, k-1); } } main(int argc, char *argv[]) { int n = 10; if(argc > 1) n = atol(argv[1]); { int i, r; struct warg w[MAXNPROC]; for(i=0;i