Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Break C++ Accept Function?

Tags:

c++

sockets

When doing socket programming, with multi-threading,

if a thread is blocked on Accept Function,

and main thread is trying to shut down the process,

how to break the accept function in order to pthread_join safely?

I have vague memory of how to do this by connection itself to its own port in order to break the accept function.

Any solution will be thankful.

Cheers

like image 341
Jae Park Avatar asked Sep 24 '12 12:09

Jae Park


2 Answers

Some choices:

a) Use non-blocking

b) Use AcceptEx() to wait on an extra signal, (Windows)

c) Close the listening socket from another thread to make Accept() return with an error/exception.

d) Open a temporary local connection from another thread to make Accept() return with the temp connection

like image 129
Martin James Avatar answered Oct 10 '22 07:10

Martin James


The typical approach to this is not to use accept() unless there is something to accept! The way to do this is to poll() the corresponding socket with a suitable time-out in a loop. The loop checks if it is meant to exit because a suitably synchronized flag was set.

An alternative is to send the blocked thread a signal, e.g., using pthread_kill(). This gets out of the blocked accept() with a suitable error indication. Again, the next step is to check some flag to see if the thread is meant to exit. My preference is the first approach, though.

like image 29
Dietmar Kühl Avatar answered Oct 10 '22 07:10

Dietmar Kühl