Hi I have written following code but when i execute it, i get an error "segmentation fault". Can anyone plz tell me why i am getting the error. I have surfed the internet for 2 days but still could not get any idea. Code is #include //#include #include #include #include void* increment(void *msg); int count = 0; int num[1]; pthread_mutex_t mutex;// = PTHREAD_MUTEX_INITIALIZER; int main() { //int num [1]; FILE *f; f=fopen("data.txt","w"); num[0]=0; fwrite(num,sizeof(num),1,f); fclose(f); pthread_t t1, t2, t3, t4, t5; pthread_mutex_init(&mutex,NULL); int tid1, tid2, tid3, tid4, tid5; char msg1[] = "Thread 1"; char msg2[] = "Thread 2"; char msg3[] = "Thread 3"; char msg4[] = "Thread 4"; char msg5[] = "Thread 5"; pthread_attr_t *attr; pthread_attr_init(attr); tid1 = pthread_create( &t1, NULL, increment, (void*)msg1); tid2 = pthread_create( &t2, NULL, increment, (void*)msg2); tid3 = pthread_create( &t3, NULL, increment, (void*)msg3); tid4 = pthread_create( &t4, NULL, increment, (void*)msg4); tid5 = pthread_create( &t5, NULL, increment, (void*)msg5); printf("Threads are created!\n"); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); pthread_join(t4, NULL); pthread_join(t5, NULL); return 0; } void *increment(void* msg) { char *message = (char*)msg; printf("%s starts: ", message); for (int i=0;i<20;i++) { pthread_mutex_lock( &mutex ); FILE* fh = fopen("data.txt", "r+"); fread(num, sizeof(num), 1, fh); num[0] = num[0]+1; printf("%d\n", num[0]); fseek(fh,0,SEEK_SET); fwrite(num, sizeof(num), 1, fh); fclose(fh); pthread_mutex_unlock( &mutex ); } pthread_exit(NULL); }
We Believe in Excellence www.aqueelmirza.cjb.net