1

Using the script below, I cannot seem to exit the threads. The script runs smoothly without issues but never exits when done. I can still see the thread alive, I have to use htop to kill them or completely exit the command line.

How can I get this script to exit and the threads to die?

def async_dns():
    s = adns.init()
    while True:
        dname = q.get()
        response = s.synchronous(dname,adns.rr.NS)[0]
        if response == 0:
            dot_net.append("Y")
            print(dname + ", is Y")
        elif response == 300 or response == 30 or response == 60:
            dot_net.append("N")
            print(dname + ", is N")
        elif q.empty() == True:
            q.task_done()

q = queue.Queue()
threads = []
for i in range(20):
    t = threading.Thread(target=async_dns)
    threads.append(t)
    t.start()

for name in names:
    q.put_nowait(name)
martineau
  • 119,623
  • 25
  • 170
  • 301
Mo. Atairu
  • 753
  • 8
  • 15
  • Fill the queue before starting the threads and let the thread function return when the queue is empty. – Klaus D. Aug 29 '16 at 02:34
  • Are thread starts inside the async_dns? – be_good_do_good Aug 29 '16 at 03:13
  • You can easily make it so all the threads exit when the main one does. See [my answer](http://stackoverflow.com/questions/38804988/what-does-sys-exit-really-do-with-multiple-threads/38805873#38805873) to the question _What does sys.exit really do with multiple threads?_ Note in your case you don't need to call `sys.exit()` explicitly, it will happen automatically after the final `for` loop at the end of the script. – martineau Aug 29 '16 at 05:16

2 Answers2

0

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

Remember to check your queue.

See the document of queue.

McGrady
  • 10,869
  • 13
  • 47
  • 69
0

Your threads are stuck in dname = q.get()

If you reaching empty queue, q.get() will wait forever for value to arrive.

You can replace get with get_nowait() but get ready to catch Queue.Empty execption

Samuel
  • 3,631
  • 5
  • 37
  • 71