SuB
SuB

Reputation: 2547

How terminate thread reading from socket c++?

In c++, "recvfrom" function is a blocking function (block thread till a packet arrive).

How can i safely terminate a thread blocked in "recvfrom" ?

Upvotes: 0

Views: 1139

Answers (2)

janm
janm

Reputation: 18359

Use the "self pipe" trick.

Open a pipe using the pipe(2) system call. Sit in a loop using select/poll/kqueue/whatever reading from the socket you care about and the pipe. When you get data from your socket, deal with it as you normally would.

To stop the thread, close the other end of the pipe in the thread that wants to stop processing. You will detect this as an EOF on the pipe, which you can then use as a signal to stop the thread processing the real socket.

Upvotes: 2

Stephan Dollberg
Stephan Dollberg

Reputation: 34608

Avoid the situation by only calling recvfrom once select/poll/epoll has returned successfully.

Like @Remy Lebeau mentioned in the comments you can pullup something like below:

while(run_flag) {
    if(check select/poll/epoll) {
         recvfrom(..)
    }
}

You can get started with epoll and with select here. There is also plenty on the internet.

A different approach would be to use asynchronous networking operations instead of threading.

I might also recommend to use boost::asio as that will simply all your networking stuff.

Upvotes: 2

Related Questions