简体   繁体   English

从多线程python中的列表中选择项目

[英]Choose Items from a List in multithreaded python

I am a beginner in python and cant figure out how to do this: I am running a python script that puts a new value every 5-10 seconds into a list. 我是python的初学者,无法弄清楚该怎么做:我正在运行一个python脚本,该脚本每5-10秒将一个新值放入一个列表中。 I want to choose these elements from the list in another multithreaded python script however per thread one value, so one value shouldnt be reused, if theres no next value, then wait until next value is present. 我想从另一个多线程python脚本的列表中选择这些元素,但是每个线程一个值,因此不应重复使用一个值,如果没有下一个值,请等待下一个值出现。 I have some code where I tried to do it but with no success: 我有一些尝试执行的代码,但是没有成功:

Script that creates values: 创建值的脚本:

values = ['a','b','c','d','e','f']
cap = []

while True:
    cap.append(random.choice(values))
    print cap
    time.sleep(5)

Script that needs these values: 需要这些值的脚本:

def adding(self):

p = cap.pop()
print (p)

However in a multithreaded environment, each thread gives me the same value, even thought I want value for each thread to be different (eg remove value already used by thread) What are my options here? 但是,在多线程环境中,每个线程都给我相同的值,甚至认为我希望每个线程的值都不同(例如,删除线程已使用的值),在这里我有哪些选择?

If I understood correctly, you want to use one thread (a producer) to fill a list with values, and then a few different threads (consumers) to remove from that same list. 如果我理解正确,您想使用一个线程(生产者)用值填充列表,然后使用几个不同的线程(消费者)从同一列表中删除。 Thus resulting with a series of consumers which have mutually exclusive subsets of the values added by the producer. 因此,产生了一系列消费者,这些消费者具有生产者添加的值的互斥子集。

A possible outcome might be: 可能的结果可能是:

Producer 制片人

cap.append('a')
cap.append('c')
cap.append('b')
cap.append('f')

Consumer 1 消费者1

cap.pop() # a
cap.pop() # f

Consumer 2 消费者2

cap.pop() # c
cap.pop() # b

If this is the behavior you want I recommend using a thread-safe object like a Queue (python 2.*) or queue (python 3.*) 如果这是您想要的行为,我建议您使用线程安全对象,例如Queue (python 2. *)或queue (python 3. *)

Here is one possible implementation 这是一种可能的实现

Producer 制片人

import Queue
values = ['a','b','c','d','e','f']
q = Queue.Queue()

while True:
    q.put(random.choice(values))
    print q
    time.sleep(5)

Consumer 消费者

val = q.get() # this call will block (aka wait) for something to be available
print(val)

Its also very important that both the producer and the consumer have access to the same instance of the of q . 生产者和消费者都可以访问q的相同实例,这一点也很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM