I've written a program that sends and receives messages through TCP sockets using std::send/recv. On rare occasion, one machine will receive a message, but not send back an answer - this causes the machine that's waiting for the answer to hang at the recv call. My thought was to split the send/recv out into a separate thread, then kill the thread if it has to wait longer than a second for an answer. I can do that by creating the send/recv thread, then making a sleep(1) call, then creating a killing thread that calls pthread_cancel on the first thread.

This works fine and dandy (albeit ineloquent), but it forces a 1 second sleep every time the function gets called. What I'd prefer to have happen is to spawn both threads, make the "kill" thread sleep for a second, and have the program wait for the send/recv thread to finish with a pthread_join function. This way, if the send/recv thread finishes, the "kill" thread tries to kill something that doesn't exist, and everyone is happy, furthermore (if my thinking is correct), the program execution time won't be effected because even though the kill thread is sleeping, or pausing, or pthread_delay_np'ing, no one is waiting on it to finish - so everyone continues on their merry way.

Is this a good way to go about it? If so, how can I make the thread sleep (sleep(1) doesn't seem to work correctly in a thread - it makes all threads sleep(1), and if I try it without a sleep, the kill thread kills the send/recv thread before it's had a good chance to finish)? As an alternative, is there a way to make the recv function time out?

edit: I've tried nanosleep, but that seem to have problems & doesn't always work as advertised. This could possiby be due to the fact that I'm writing plugins for another application that may set some compiler flags that disables this ability? I'm not sure.