我想使用2个线程遍历列表。一个来自领先,另一个来自尾随,并在每次迭代中将元素放在Queue
中。但在将值放入Queue
之前,我需要检查Queue
(当其中一个线程将该值放在Queue
中时)的值是否存在,所以当发生这种情况时,我需要停止线程并返回遍历值的列表为每个线程。多线程检查队列中的成员并停止线程
这是我到目前为止已经试过:
from Queue import Queue
from threading import Thread, Event
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args,
**self._Thread__kwargs)
def join(self):
Thread.join(self)
return self._return
main_path = Queue()
def is_in_queue(x, q):
with q.mutex:
return x in q.queue
def a(main_path,g,l=[]):
for i in g:
l.append(i)
print 'a'
if is_in_queue(i,main_path):
return l
main_path.put(i)
def b(main_path,g,l=[]):
for i in g:
l.append(i)
print 'b'
if is_in_queue(i,main_path):
return l
main_path.put(i)
g=['a','b','c','d','e','f','g','h','i','j','k','l']
t1 = ThreadWithReturnValue(target=a, args=(main_path,g))
t2 = ThreadWithReturnValue(target=b, args=(main_path,g[::-1]))
t2.start()
t1.start()
# Wait for all produced items to be consumed
print main_path.join()
我用ThreadWithReturnValue
,这将创建一个返回值自定义线程。
并在成员检查我用下面的功能:
def is_in_queue(x, q):
with q.mutex:
return x in q.queue
现在,如果我第一次启动t1
然后t2
我会得到12 a
然后一个b
那么它不会做任何事情,我需要手动终止python!
但是,如果我先运行t2
然后t1
我会得到以下结果:
b
b
b
b
ab
ab
b
b
b
b
a
a
所以我的问题是,为什么蟒蛇胎面在这种情况下,有什么不同?以及如何终止线程并使它们彼此通信?
看看这里http://pymotw.com/2/multiprocessing/communication.html ...你更感兴趣的是管理共享状态 – OWADVL
@OWADVL声音有用,我会看到的!谢谢! – Kasramvd
您是否有从列表两端进行迭代的实际要求,或者您是否只是将其作为划分任务的一种方式? – 101