I am writing an network application.
and have some problem regarding thread race condition.
“cd” is a socket descriptor.
one of my thread retrieves socket descriptor
and send some data through the socket.
lets say map_sd returns 5.
however another thread might close the socket 5 and
reassign another. which will destroy the logic of program.
// wait until there is valid descriptor mapping
while( !(cd = map_sd( sd )) ){
sleep(1);
}
// forward PAYLOAD header
if( send(cd, &payload, sizeof(PAYLOAD), MSG_NOSIGNAL) < 0 ){
printf("send fail 813\n");
}
what I want is to make the code above “atomic”
how can I do this when I am using pthread library in linux??
thank you in advance.
You need a condition variable and a mutex:
In the thread passing cd:
In the thread waiting for cd:
That should be it – you use a condition variable and a lock for exclusive access and notifying the other thread that a resource is now available.
pthread_cond_wait()releases the lock to wait and will reacquire it once it has been notified by the other thread withpthread_cond_signal().Edit: formatting.