Python execute threads by order

前端 未结 1 1560
灰色年华
灰色年华 2021-01-28 04:36

I have the following code:

import threading

def send_to_server(lst):
    #Some logic to send the list to the server.


while 1:
    lst = []
    for i in         


        
1条回答
  •  醉梦人生
    2021-01-28 05:18

    You want to use Queue, the threadsafe queue class in python. I imagine you want a thread to put things in the queue, and a thread to act on them serially like so:

    q = Queue.Queue()
    t1 = threading.Thread(target=fill_q,args(q, lst))
    t2 = threading.Thread(target=consume_q,args(q, lst))
    t1.start()
    t2.start()
    
    def fill_q(q, lst):
        for elem in lst:
            q.put(elem)
    
    def consume_q(q, lst):
        for i in range(len(lst)):
            send_to_server(q.get())
    

    If you are interested in performance, you may want to read up on the GIL in python, here https://wiki.python.org/moin/GlobalInterpreterLock

    0 讨论(0)
提交回复
热议问题