Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions test_zeroconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,20 @@ def test_dnstext_repr_works():
# from working when the text was longer than 10 bytes
text = DNSText('irrelevant', None, 0, 0, b'12345678901')
repr(text)


def test_close_waits_for_threads():
class Dummy(object):
def add_service(self, zeroconf_obj, service_type, name):
pass
def remove_service(self, zeroconf_obj, service_type, name):
pass

z = Zeroconf()
z.add_service_listener('_privet._tcp.local.', listener=Dummy())
z.close()
assert not z.browsers[0].is_alive()


if __name__ == '__main__':
unittest.main()
26 changes: 25 additions & 1 deletion zeroconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1671,14 +1671,38 @@ def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT):
'Should not happen, sent %d out of %d bytes' % (
bytes_sent, len(packet)))

def _check_threads(self):
"""Check if any threads are still active.

Returns:
True if the Reaper or Engine started by this object is still alive or
if any ServiceBrowser known to this object is still alive. Otherwise
False.
"""
threads = [self.reaper, self.engine] + self.browsers
for t in threads:
if isinstance(t, threading.Thread) and t.is_alive():
return True
return False

def close(self):
"""Ends the background threads, and prevent this instance from
servicing further queries."""
servicing further queries.

This operation blocks until all threads exit.
"""
global _GLOBAL_DONE
if not _GLOBAL_DONE:
_GLOBAL_DONE = True
self.notify_all()
self.engine.notify()
self.unregister_all_services()

# Wait for threads to actually die before destroying the sockets
threads_alive = self._check_threads()
while threads_alive:
time.sleep(0.01)
threads_alive = self._check_threads()

for s in [self._listen_socket] + self._respond_sockets:
s.close()