xref: /netbsd-src/external/bsd/unbound/dist/libunbound/python/doc/examples/example2.rst (revision 0cd9f4ecf44538bbdd5619b5b2081449960ab3e6)
13b6c3722Schristos.. _example_setup_ctx:
23b6c3722Schristos
33b6c3722SchristosLookup from threads
4*0cd9f4ecSchristos===================
53b6c3722Schristos
63b6c3722SchristosThis example shows how to use unbound module from a threaded program.
73b6c3722SchristosIn this example, three lookup threads are created which work in background.
83b6c3722SchristosEach thread resolves different DNS record.
93b6c3722Schristos
10*0cd9f4ecSchristosSource code
11*0cd9f4ecSchristos-----------
12*0cd9f4ecSchristos
133b6c3722Schristos::
143b6c3722Schristos
153b6c3722Schristos    #!/usr/bin/python
163b6c3722Schristos    from unbound import ub_ctx, RR_TYPE_A, RR_CLASS_IN
173b6c3722Schristos    from threading import Thread
183b6c3722Schristos
193b6c3722Schristos    ctx = ub_ctx()
203b6c3722Schristos    ctx.resolvconf("/etc/resolv.conf")
213b6c3722Schristos
223b6c3722Schristos    class LookupThread(Thread):
233b6c3722Schristos        def __init__(self,ctx, name):
243b6c3722Schristos            Thread.__init__(self)
253b6c3722Schristos            self.ctx = ctx
263b6c3722Schristos            self.name = name
273b6c3722Schristos
283b6c3722Schristos        def run(self):
293b6c3722Schristos            print "Thread lookup started:",self.name
303b6c3722Schristos            status, result = self.ctx.resolve(self.name, RR_TYPE_A, RR_CLASS_IN)
313b6c3722Schristos            if status == 0 and result.havedata:
323b6c3722Schristos                print "  Result:",self.name,":", result.data.address_list
333b6c3722Schristos
343b6c3722Schristos    threads = []
353b6c3722Schristos    for name in ["www.fit.vutbr.cz","www.vutbr.cz","www.google.com"]:
363b6c3722Schristos        thread = LookupThread(ctx, name)
373b6c3722Schristos        thread.start()
383b6c3722Schristos        threads.append(thread)
393b6c3722Schristos
403b6c3722Schristos    for thread in threads:
413b6c3722Schristos        thread.join()
42