linux - sem_init on ubuntu using C-Language -
i working on code uses pthread , semaphore libraries. here code dose not work , think because of sem_init
function. new in c , don't know how use sem_init
, sem_open
, sem_wait
, sem_post
. can give me advice??
#include <sys/mman.h> #include <math.h> #include <wait.h> #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <sys/sem.h> #include <sys/types.h> #include <unistd.h> #include<fcntl.h> sem_t sem1,sem2; float calculate(int a,int b) { float d = ((a *a) + (b*b))/2; return d; } int main() { int q; int i,j,x; float *maddress, m, sum; maddress=mmap(null,sizeof(float),prot_read|prot_write,map_shared,-1,0); sem_init(&sem2,0,1); sem_init(&sem1,0,0); sem_open("sem2",o_creat); sem_open("sem1",o_creat); if((q = sem_init(&sem1,1,0))!=0) printf("error in create\n"); for(i=1;i<=10;i++) { j=fork(); if(j==0) { printf("the child %d executing\n",i); m=calculate(i-1,i); printf("child %d calculated value: %f\n",i,m); sem_wait(&sem2); maddress=&m; sem_post(&sem1); exit(exit_success); } } for(j=1;j<=10;j++) { wait(&x); if(wifexited(x)) { sem_wait(&sem1); sum=sum+ (*maddress); sem_post(&sem2); } } printf("the final result is: %f \n",sum); sem_close(&sem1); sem_close(&sem2); return 0; }
(1) there 2 kinds of posix semaphores - named , unnamed - , mixing both. unnamed semaphores use sem_init
, sem_destroy
. named use sem_open
,sem_close
, sem_unlink
.
(2) assuming want unnamed semaphores, fine related (i.e. forked) processes doing, must put semaphores shared memory before start forking. putting semaphore process memory won't shared between children , parent because every child own copy of memory , therefore, in effect, own set of semaphore not related other process.
your program hang forever in parent @ sem_wait(&sem1)
because children signaling entirely different copy of sem1.
Comments
Post a Comment