Re: Closing an accepting BSD socket from a different thread


Paul Sokolovsky
 

Hello Stephan,

On Wed, 22 May 2019 16:10:19 +0200
"Stephan Gatzka" <stephan.gatzka@...> wrote:

Hello!

I've a thread blocking on an zsock_accept(). After a certain time
another thread decides that this socket is no longer required and
calls zsock_close() on that socket.
Paradigmatically correct approach to this situation is:

1. Avoid sharing I/O resources (not just sockets) across different
threads.
2. If/when you can't avoid it, you need to synchronize access to those
resources from different threads using synchronization primitives
(mutexes, semaphores, etc.)

Now the thread blocking on
zsock_accept() crashes horribly deep down in zephyrs socket
implementation.
Eventually, we'll need to catch and fix such cases. But the only
visible effect for well-behaving applications following the guidelines
above will be bloating code size in the Zephyr network stack/socket
implementation (so hopefully, we won't get bad community stereotypes
due to that). If you have a small reproduction testcase for the issue,
definitely please submit it at
https://github.com/zephyrproject-rtos/zephyr/issues

My question is how I can safely "unblock" the thread waiting in the
zsock_accept()?
A way to not block forever in accept() call is to use timed poll() on
that socket. The thread issuing the poll() call would be the best
party to know when to close this socket (e.g., if there's no
activity during some period of time). Other threads could signal the
owner thread that they want something to be done to the socket via flag
variables. E.g., following is a well-know pattern:

=== main loop thread ===
while (!should_exit) {
...
poll(..., MAIN_LOOP_PERIOD);
...
}
close(...);
exit();

=== other threads ===
should_exit = true;


Thanks,
Stephan
--
Best Regards,
Paul

Linaro.org | Open source software for ARM SoCs
Follow Linaro: http://www.facebook.com/pages/Linaro
http://twitter.com/#!/linaroorg - http://www.linaro.org/linaro-blog

Join users@lists.zephyrproject.org to automatically receive all group messages.