Concurrently run two functions that take parameters and return lists?

前端 未结 2 1626
花落未央
花落未央 2021-01-23 03:14

I understand that two functions can run in parallel using multiprocessing or threading modules, e.g. Make 2 functions run at the same time and Python m

2条回答
  •  被撕碎了的回忆
    2021-01-23 04:01

    Thread's target function cannot return a value. Or, I should say, the return value is ignored and as such, not communicated back to spawning thread. But here's a couple things you can do:

    1) Communicate back to spawning thread using Queue.Queue. Note the wrapper around the original functions:

    from threading import Thread
    from Queue import Queue
    
    def func1(x):
        return [i*i for i in x]
    
    def func2(x):
        return [i*i*i for i in x]
    
    nums = [1,2,3,4,5]
    
    def wrapper(func, arg, queue):
        queue.put(func(arg))
    
    q1, q2 = Queue(), Queue()
    Thread(target=wrapper, args=(func1, nums, q1)).start() 
    Thread(target=wrapper, args=(func2, nums, q2)).start() 
    
    print q1.get(), q2.get()
    

    2) Use global to access result lists in your threads, as well as the spawning process:

    from threading import Thread
    
    list1=list()
    list2=list()
    
    def func1(x):
        global list1
        list1 = [i*i for i in x]
    
    def func2(x):
        global list2
        list2 = [i*i*i for i in x]
    
    nums = [1,2,3,4,5]
    
    Thread(target = func1, args=(nums,)).start()
    Thread(target = func2, args=(nums,)).start()
    
    print list1, list2
    

提交回复
热议问题