I wrote the following program:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define perror2(s,e) fprintf(stderr,"%s: %s\n",s,strerror(e))
int nthr;
int cbits;
pthread_mutex_t mtx1=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t begin=PTHREAD_COND_INITIALIZER;
void *worker(void *iter) {
int i,err;
printf("I am worker with id %d , iter=%d\n",pthread_self(),(long int *)iter); /* Here shouldn't it be *(long int *)iter ?*/
/* for(i=0;i<nthr;i++)
if(err=pthread_join(tids[i],NULL)) {
perror2("pthread_join",err);
exit(1);
*/// }
pthread_exit(NULL);
}
void *controller(void *ids) {
int i;
int *wids=(int *)ids;
long int terms;
srand48((long int)time(NULL));
terms=lrand48()%(long int)(pow(double(2),(double)cbits));
printf("Controller :%d",cbits);
printf(".Workers id's :");
for(i=0;i<nthr;i++)
printf(" , %d",*wids++); /* Here it is as it should be */
printf("\n");
pthread_exit(NULL);
}
main(int argc,char** argv) {
int i,err;
long int iter;
pthread_t *wids,cid;
cbits=atoi(argv[3]);
if(argc!=4) {
printf("Usage: pibythr <nthr> <wbits> <cbits>\n");
exit(1);
}
nthr=atoi(argv[1]);
if((wids=(pthread_t *)malloc(nthr*sizeof(pthread_t)))==NULL) {
perror("malloc");
exit(1);
}
srand48((long int)getpid());
for(i=0;i<nthr;i++) {
iter=lrand48()%(long int)(pow((double)2,(double)atoi(argv[2])));
if(err=pthread_create(wids+i,NULL,worker,(void *)iter)) {
perror2("pthread_create",err);
exit(1);
}
}
if(err=pthread_create(&cid,NULL,controller,(void *)wids)) {
perror2("pthread_create",err);
exit(1);
}
/* if(err=pthread_join(cid,NULL)) {
perror2("pthread_join",err);
exit(1);
}
*/ printf("main:All threads terminated\n");
pthread_exit(NULL);
}
My question is about the two lines with the comments next to printf's.
In the first one if i put *(long int*)iter instead of (long int*)iter it prints "Segmentation fault"
Why is this happening?Why does it work properly by writing (long int*)iter?
Shouldn't this line be similar to the second with the *wids?
Thank you in advance.