我正在创建两个进程。将一个int值添加到一个Mutliprocessing.Queue从1到5.另一个将添加到Queue一次然后它将循环10秒并尝试从队列中读取值。
为什么我的第二个进程在第一个线程中没有将项添加到队列中?我假设在创建Multiprocessing.Queue时,我可以从一个进程添加它,并且它可以被另一个进程读取。看起来它只是添加到传递的Qeueu而不是父队列。我是否可以从父级创建的2个不同进程中将项添加到某种类型的队列?
from multiprocessing import Process, Queue
import time
def f(q):
for a in range(5):
print "Adding to Q!"
time.sleep(1)
q.put(a)
def g(q):
i = 0
v = True
q.put("Adding to this q")
while v == True:
time.sleep(1)
i = i + 1
print "Get slept time " , i
try:
print "From the q " + str(q.get(True,1))
except:
print "Empty"
if i == 10:
v = False
if __name__ == '__main__':
q = Queue(10)
print "First process"
p = Process(target=f, args=(q,))
p.start()
print "Second Process"
p1 = Process(target=g, args=(q,))
p1.start()
p.join()
p1.join()
我的输出截至目前。 **它不是所需的输出**
First process
Second Process
Adding to Q!
Get slept time 1
From the q Adding to this q
Adding to Q!
Get slept time 2
Adding to Q!
Empty
Get slept time 3
Adding to Q!
Empty
Get slept time 4
Adding to Q!
Empty
Get slept time 5
Empty
Get slept time 6
Empty
Get slept time 7
Empty
Get slept time 8
Empty
Get slept time 9
Empty
Get slept time 10
Empty
答案 0 :(得分:1)
print "From the q " + q.get(True,1)
中
您的例外是TypeError: cannot concatenate 'str' and 'int' objects
您最好使用print "From the q {}".format(q.get(True,1))
@tiggles
编辑后编辑:
从队列中读/写没有问题。
这里是正常的代码示例:
from multiprocessing import Process, Queue
import time
def f(q):
for a in range(5):
time.sleep(1)
q.put(a)
def g(q):
i = 0
v = True
q.put("Adding to this q")
while v == True:
time.sleep(1)
i = i + 1
print "Get slept time " , i
try:
print "From the q {}".format(q.get(True,1))
except Exception as e:
print 'exception raised {} {}'.format(e, type(e))
print "Empty"
if i == 10:
v = False
if __name__ == '__main__':
q = Queue(10)
p = Process(target=f, args=(q,))
p.start()
p1 = Process(target=g, args=(q,))
p1.start()
p.join()
p1.join()
print q.qsize(), q.empty()
和结果:
Get slept time 1
From the q Adding to this q
Get slept time 2
From the q 0
Get slept time 3
From the q 1
Get slept time 4
From the q 2
Get slept time 5
From the q 3
Get slept time 6
From the q 4
Get slept time 7
exception raised <class 'Queue.Empty'>
Empty
Get slept time 8
exception raised <class 'Queue.Empty'>
Empty
Get slept time 9
exception raised <class 'Queue.Empty'>
Empty
Get slept time 10
exception raised <class 'Queue.Empty'>
Empty
0 True
有任何问题吗?