#include #include #include #include #include double mi, sigma; unsigned long tn[] = {0, 0}; unsigned long n = 20000000; double tmi[] = {.0, .0}; double *values; pthread_t ts[2]; pthread_attr_t atr; pthread_mutex_t sync_us; pthread_cond_t move_on; void * obrada(void *id){ int tid = (int)id; unsigned long li, ln = 10000000, j; double lmi, lsigma, lsum = 0, b; char ime[15]; FILE *f; li = 0; for(j = tid * 10 + 1; j <= (tid + 1) * 10; j+=1){ sprintf(ime, "dat%d.txt", j); //printf("%ld krecem na %s\n", tid, ime); f = fopen(ime, "r"); fscanf(f,"%lf",&b); while(!feof(f)){ values[li + ln * tid] = b; lsum += b; li += 1; fscanf(f, "%lf",&b); } fclose(f); //printf("%ld gotov sa %s\n", tid, ime); } pthread_mutex_lock(&sync_us); tn[tid] = li; tmi[tid] = lsum; if(tn[(tid + 1) % 2] == 0){ //sta je sa drugom niti? pthread_cond_wait(&move_on, &sync_us); //ili je cekam pa da radim dalje... mi = (tmi[0] + tmi[1]) / (tn[0] + tn[1]); sigma = 0; for(j = 0; j < n; j++) sigma += (values[j] - mi)*(values[j] - mi); sigma /= n; sigma = sqrt(sigma); } else{ //ili mene ceka pthread_cond_signal(&move_on); } pthread_mutex_unlock(&sync_us); pthread_exit(NULL); } int main(){ values = (double*)malloc(sizeof(double)*n); pthread_mutex_init(&sync_us, NULL); pthread_cond_init (&move_on, NULL); pthread_attr_init(&atr); pthread_attr_setdetachstate(&atr, PTHREAD_CREATE_JOINABLE); pthread_create(&ts[0], &atr, obrada, (void *)0); pthread_create(&ts[1], &atr, obrada, (void *)1); pthread_join(ts[0], NULL); pthread_join(ts[1], NULL); pthread_attr_destroy(&atr); pthread_mutex_destroy(&sync_us); pthread_cond_destroy(&move_on); printf("%lf\n", sigma); pthread_exit(NULL); return 0; }