rajeshwari
Programmer
hello everyone.
i am trying to write a multithreaded prg with posix threads and semaphores.
the code is as follows
#define parg 2
#define NTHREADS 5
void *do_job(void *);
sem_t sid[NTHREADS];
pthread_t tid[NTHREADS];
int main()
{
int i,ret;
printf("about to create semaphores\n"
for(i=1;i<=4;i++)
{
ret=sem_init(&sid,0,0);
if(ret==-1)
printf("error in creating semaphore\n"
else
printf("semaphore %d created\n",i);
}
ret=sem_init(&sid[5],0,5);
if(ret==-1)
printf("error in creating semaphore\n"
else
printf("semaphore 5 created\n"
for(i=1;i<=NTHREADS;i++)
{
ret=pthread_create(&tid,NULL,do_job,NULL);
if(ret==-1)
printf("error in creating thread\n"
else
printf("thread %d created\n", i);
}
for(i=1;i<=NTHREADS;i++)
pthread_join(tid,NULL);
printf("Threads have terminated"
for(i=1;i<=NTHREADS;i++)
sem_destroy(&sid);
}
void *do_job(void *i)
{
int x,j,m;
pthread_t t;
x=(int)i;
t=pthread_self();
printf("entered do job\n"
int sleep_time=2;
for(x=1;x<=NTHREADS;x++)
{
if(tid[x]==t)
{
if(x==1)
j=6;
else
j=x+1;
sem_wait(&sid[j]);
printf("thread %d is sleeping now\n",thr_self());
sleep(sleep_time);
printf("Thread %d is now waking up\n",thr_self());
sem_post(&sid[x]);
}
}
return(NULL);
}
can someone please tell me what is it that i am doing worng. I want each thread to run individually one after another.
i am trying to write a multithreaded prg with posix threads and semaphores.
the code is as follows
#define parg 2
#define NTHREADS 5
void *do_job(void *);
sem_t sid[NTHREADS];
pthread_t tid[NTHREADS];
int main()
{
int i,ret;
printf("about to create semaphores\n"
for(i=1;i<=4;i++)
{
ret=sem_init(&sid,0,0);
if(ret==-1)
printf("error in creating semaphore\n"
else
printf("semaphore %d created\n",i);
}
ret=sem_init(&sid[5],0,5);
if(ret==-1)
printf("error in creating semaphore\n"
else
printf("semaphore 5 created\n"
for(i=1;i<=NTHREADS;i++)
{
ret=pthread_create(&tid,NULL,do_job,NULL);
if(ret==-1)
printf("error in creating thread\n"
else
printf("thread %d created\n", i);
}
for(i=1;i<=NTHREADS;i++)
pthread_join(tid,NULL);
printf("Threads have terminated"
for(i=1;i<=NTHREADS;i++)
sem_destroy(&sid);
}
void *do_job(void *i)
{
int x,j,m;
pthread_t t;
x=(int)i;
t=pthread_self();
printf("entered do job\n"
int sleep_time=2;
for(x=1;x<=NTHREADS;x++)
{
if(tid[x]==t)
{
if(x==1)
j=6;
else
j=x+1;
sem_wait(&sid[j]);
printf("thread %d is sleeping now\n",thr_self());
sleep(sleep_time);
printf("Thread %d is now waking up\n",thr_self());
sem_post(&sid[x]);
}
}
return(NULL);
}
can someone please tell me what is it that i am doing worng. I want each thread to run individually one after another.