Python按顺序执行线程 [英] Python execute threads by order

查看:823
本文介绍了Python按顺序执行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

导入线程

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


while 1:
    lst = []
    for i in range(1000):
        lst.append(i)
    task = threading.Thread(target=send_to_server,args(copy(lst),))
    task.start()

我有几个问题:

1)使用线程的想法是因为发送到服务器需要时间,并且我想继续
不间断地生成数据.
此代码的问题是,如果我创建了线程#3,并花费很长时间进行处理,那么此时将启动线程#4. 我想确保每个列表都将由我创建的另一个列表发送到服务器,这意味着线程#3将在线程#4之前将数据发送到服务器.
我了解我需要使用一个队列,但我不知道该怎么做.

1) The idea for using threads is because sending to server takes time and I want to continue
generating the data without any stop.
The problem with this code is that if I created thread #3 and its taking long time to process,
By that time thread #4 will be started. I want to assure that every list will be sent to server by the other I created it, means thread #3 will send to server the data before thread #4.
I understand that I need to use a Queue, but I don't know exactly how.

2)我应该使用lst的副本吗?或者我不确定是否也可以使用lst.

2)Should I use copy of lst? or I can use lst as well, I'm not sure.

推荐答案

您要使用Queue,这是python中的线程安全队列类.我想您想让一个线程将事物放入队列中,并让一个线程对它们依次进行操作,如下所示:

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())

如果您对性能感兴趣,则可能需要在python中阅读GIL,这里 https://wiki.python.org/moin/GlobalInterpreterLock

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

这篇关于Python按顺序执行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆