Possible deadlock situation in the below code

H

Harry

semaphore.cpp

union semun
{
int val;
struct semid_ds *buf;
ushort *array;
};
union semun mysemun;

int semRead(int *part,int semid)
{
int result;

result = semctl(semid , 0, GETVAL, mysemun);
if ( result < 0 )
{
return(-1);
}
else if (result)
{
result = semctl(semid , 1, GETVAL, mysemun);
if (result < 0) {
return -1;
}
else
*part = 1;
} else
*part = 0;

return 0;
}
int semSet( int part,int semid )
{
int result, value, secondPart;

if ( part != 0 && part != 1 )
return -1;
else
secondPart = (!part);

if ( (result = semRead(&value)) < 0 )
return -2;

/* result contains info about correct region of shared memory */
if ( value == part )
return 0;

mysemun.val = 0;
while ( semctl ( semid,part,SETVAL,mysemun ) != 0 )
{
sleep ( 1 );
}
mysemun.val = 1;
while ( semctl ( semid,secondPart,SETVAL,mysemun ) != 0 )
{
sleep ( 1 );
}

return 0;

}

int initSemaphore(int* semid)
{

int _sem_key_ =1014;;

do
*semid = semget (_sem_key_,2,0644 | IPC_CREAT );
while( *semid == -1 );
return 0;
}


client.cpp
int main()
{
int semid=0,part=0;
initSemaphore(&semid);
semRead(part,semid);
cout<<"Active Part is "<<part<<endl;
return 0;
}


server.cpp
int main()
{
int semid=0,part=0,newPart=0;
initSemaphore(&semid);

cout<<"Enter the part to make active(0,1)"<<endl;
cin>>newPart;
if(! semSet(part,semid))
cout<<"Part Already Active"<<endl;

semRead(part,semid);
cout<<"New Active Part "<<part<<endl;
return 0;
}


Hi Gurus,
Can I have deadlock situation in the above code if both server and
client are running simultaneously.
A server instance can be only one but client can have multiple
instances.

Thanks in advance for answering my queries.
~HPS~
 
S

Shao Miller

Down the hall and to the left, you will find comp.lang.c++.

Offered just in case it'd be more beneficial for you.
 
E

Eric Sosman

semaphore.cpp
[...]

This is comp.lang.c. The comp.lang.c++ newsgroup is down
the hall to your right, past the water cooler. (Don't try to
drink from it; it's only a template.)
[...]
Can I have deadlock situation in the above code[...]

Would it surprise you to learn that there's a newsgroup
called comp.programming.threads? And that it's not about sewing?
 
S

Seebs

Would it surprise you to learn that there's a newsgroup
called comp.programming.threads? And that it's not about sewing?

/me sadly closes "shirt.c" and deletes it.

-s
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top