c - Pi calculator with mutex Synchronization -
finishing assignment here. got code work , calculate pie except random values receive following errors:
./piesync 10 3 pi computed 10 terms in 3 threads 3.14183961892940200045 * error in `./piesync': free(): invalid next size (fast): 0x0000000001ca3010 *
./piesync 100 5 * error in `./piesync': double free or corruption (out): 0x0000000000ee5040 *
i know might array or mutex cant figure out what.
code:
//pini vaknine #include <stdio.h> #include <stdlib.h> #include <pthread.h> //global variables int n, t; double gpie = 3.0; pthread_mutex_t mutex; //pie function void* pie_runner(void* arg) { long j = (long)arg; long lower = (n/t)*(j-1)+1; long upper = ((n/t)*(j)); double mypartialsum = 0; //printf("lower=%lu upper=%lu\n",lower , upper); for(long = lower; <= upper; i++) { if(i % 2 == 0){ mypartialsum -= 4.0/((2*i)*(2*i+1)*(2*i+2)); //printf("vsum %lu = %f\n", j, vsum[j]); } else{ mypartialsum += 4.0/((2*i)*(2*i+1)*(2*i+2)); //printf("vsum %lu = %f\n", j, vsum[j]); } } pthread_mutex_lock (&mutex); gpie = gpie + mypartialsum; pthread_mutex_unlock (&mutex); pthread_exit(0); //return null; } int main(int argc, char **argv) { if(argc != 3) { printf("error: must send 2 parameters, sent %d\n", argc-1); exit(1); } n = atoi(argv[1]); t = atoi(argv[2]); if(n <= t) { printf("error: number of terms must greater number of threads.\n"); exit(1); } //launch threads pthread_attr_t attr; pthread_t *tids = (pthread_t *) calloc(t, sizeof(pthread_t)); if(tids == null) { fprintf(stderr, "memory allocation problem\n"); exit(1); } pthread_mutex_init(&mutex, null); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, pthread_create_joinable); for(long = 1; i<=t; i++) { int r = pthread_create(&tids[i], &attr, pie_runner, (void*)i); if(r<0) { printf("error: pthread_create() returned %d\n", r); exit(2); } } //wait threads... for(int k = 1; k<=t; k++) { pthread_join(tids[k], null); } printf("pi computed %d terms in %d threads %.20f\n", n, t, gpie); pthread_mutex_destroy(&mutex); pthread_attr_destroy(&attr); free(tids); return 0; }
you indexing out of range of array. have allocated array t
elements here
pthread_t *tids = (pthread_t *) calloc(t, sizeof(pthread_t));
but index incorrectly, here
for(int k = 1; k<=t; k++) { pthread_join(tids[k], null); }
and other instances too. in c index array 0
loop should be
for(int k=0; k<t; k++)
Comments
Post a Comment