Python performing multiple tasks
Question: I have an endpoint in my API, which actually get data from different
datasources, what I am trying to do is send request to all the datasources at
once and as soon as I get result from once datasource return the result to
user (terminate all remaining requests if possible).

What are good libraries in python that can be used? Any Example would be great
help

Thanks


Answer: You can use the
[multiprocessing](https://docs.python.org/2/library/multiprocessing.html)
library for this:

    
    
    from multiprocessing import Process, Queue
    import time
    q = Queue()
    
    def some_func1(arg1, arg2, q):
        #this one will take longer, so we'll kill it after the other finishes
        time.sleep(20)
        q.put('some_func1 finished!')
    
    def some_func2(arg1, arg2, q):
        q.put('some_func2 finished!')
    
    proc1 = Process(target=some_func1,
                               args = ('arga', 'argb', q))
    proc2 = Process(target=some_func2,
                               args = ('arg1', 'arg2', q))
    proc1.start()
    proc2.start()
    
    #this will be the result from the first thread that finishes.
    #At this point you can wait for the other threads or kill them, or whatever you want.
    result = q.get()
    print result
    #if you want to kill all the procs now:
    proc1.terminate()
    proc2.terminate()
    

**EDIT: Use the Queue in Multiprocessing for this as it's process safe.**

