Reputation: 878
I have an application which connected to some server. It can send data synchronously (send and wait answer) and receive data asynchronously. I made 2 threads. In the first thread in the infinity loop I send data and wait answer. In the second thread I'm cathing data from server and push they in queue. But, if happened some errors when I send data (in the first thread) I have to close socket. And how can I check in the second thread that socket is closed?
Code in the second thread:
while (processing) {
nbytes = recv(socketDesc, canFrame, sizeof(data), 0);
if (nbytes > 0) {
push_queue(data);
}
if (nbytes < 0) {
throw "Error in read data from socket!";
}
}
If I closed socket in the first thread in the second thread function recv
does not take error. Now I use timeout, like this:
setsockopt(this->socketDesc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(this->socketDesc, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
When error happens when I don't get answer from server (in the first thread) I set variable processing
to false and after timeout expires (in function recv
) loop is ended. Can I Check of socket closure at once in function recv
?
Upvotes: 0
Views: 98
Reputation:
Here's how you ensure that you don't close the socket while the reading thread is reading.
You have 2 shared boolean variables protected by a mutex:
bool reading = false;
bool closed = false;
All accesses to these are are preceded by locking the mutex, and succeeded by unlocking it.
The writing thread:
closed
to truereading
to become false
The reading thread:
closed
is not true
. If it isn't:
reading
to true
reading
to false
Upvotes: 1
Reputation:
There is no timely way of determining that you have closed the socket. You need a variable shared between both threads and protected by a mutex. The first thread can set the variable if it closes the socket, and the second thread should check it before doing a recv
.
Upvotes: 1