添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

用多线程和队列解决生产者、消费者问题 时程序报错:

Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "E:/yuyinshibie/duilie_duoxiancheng.py", line 111, in producer
chunk = stream.read(CHUNK_SIZE)
File "E:\python3.6.3-envs\lib\site-packages\pyaudio.py", line 608, in read
return pa.read_stream(self._stream, num_frames, exception_on_overflow)
OSError: [Errno -9983] Stream is stopped

原因:由于在python 的函数参数中没有加入self导致的。

参考例子:| Python 多线程|Queue队列|生产者消费者模式|

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import Queue
import random
import time
class Producter(threading.Thread):
    """生产者线程"""
    def __init__(self, t_name, queue):
        self.queue = queue
        threading.Thread.__init__(self, name=t_name)
    def run(self):
        for i in range(10):
            randomnum = random.randint(1, 99)
            self.queue.put(randomnum)
            print 'put num in Queue %s' %  randomnum
            time.sleep(1)
        print 'put queue done'
class ConsumeEven(threading.Thread):
    """奇数消费线程"""
    def __init__(self, t_name, queue):
        self.queue = queue
        threading.Thread.__init__(self, name=t_name)
    def run(self):
        while True:
                queue_val = self.queue.get(1, 3)
            except Exception, e:
                print e
                break;
            if queue_val % 2 == 0:
                print 'Get Even Num %s ' % queue_val
            else:
                self.queue.put(queue_val)
q = Queue.Queue()
pt = Producter('producter', q)
ce = ConsumeEven('consumeeven', q)
ce.start()
pt.start()
pt.join()
ce.join()

下面是一对多(1个生产者对多个消费者)例子( 最好用class来定义生产者和消费者,尽量不要用def来定义 ):

# -*- coding:utf-8 -*-
import threading,time
import queue
# 最多存入10个
q = queue.Queue(maxsize=10)
def producer(name):
    count = 1
    while True:
           # 生产一块骨头
            q.put("骨头 %s" % count )
            print("生产了骨头",count)
            count +=1
            time.sleep(0.3)
def consumer(name):
    while True:
        print("%s 取到[%s] 并且吃了它" %(name, q.get()))
        time.sleep(1)
        # 告知这个任务执行完了
        q.task_done()
# 生成线程
p = threading.Thread(target=producer,args=("德国骨科",))
c = threading.Thread(target=consumer,args=("陈狗二",))
d = threading.Thread(target=consumer,args=("吕特黑",))
# 执行线程
p.start()
c.start()
d.start()
用多线程和队列解决生产者、消费者问题时程序报错:Exception in thread Thread-1:Traceback (most recent call last): File "D:\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "D:\Python36\lib\t... import thread ing class runScript Thread ( thread ing. Thread ): def __init__(self, funcName, *args): thread ing. Thread .__init__(self) self.args = args self.funcName = funcName def run(self):