python中生产者消费者线程问题
高洛峰
高洛峰 2017-04-18 10:27:07
0
2
610

在使用python的多线程时,使用了生产者消费者模式,一般都是消费者接受生产者的数据执行某些操作,但是现在这个消费者线程遇到了异常,需要终止执行,但是生产者线程因为还在生产数据,主线程在等待它执行完。目前想当消费者线程遇到错误时能够通知生产者线程,我挂了,你也结束吧。请问大家有什么好的实现方法

import threading

class Producer(threading.Thread):

    def __init__(self, queue):
        super(Producer, self).__init__()
        self.queue = queue

    def run(self):
        while True:
            for i in range(10):
                self.queue.put(i)

class Consumer(threading.Thread):

    def __init__(self, queue):
        super(Consumer, self).__init__()
        self.queue = queue

    def run(self):
        while True:
            try:
                data = self.queue.get()
                print data
                if data == 5:
                    raise ValueError('over')
            except ValueError as e:
                #通知生产者结束
                #如何实现?
            
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
PHPzhong

我的方法:
添加一个 flag 标识。

先看结果吧:

更多废话也不多说了,show u the code

#!/usr/bin/python
# coding=utf-8
import threading
import time


class Producer(threading.Thread):

    def __init__(self, queue, flag):
        super(Producer, self).__init__()
        self.queue = queue
        self.flag = flag

    def run(self):
        while True:
            length = max(self.queue) + 1
            print "============================= producer queue", self.queue
            self.queue.append(length)
            print 'flag length=', len(self.flag)
            if len(self.flag) == 0:
                print "producer 我也结束了"
                break
            time.sleep(2)


class Consumer(threading.Thread):

    def __init__(self, queue, flag):
        super(Consumer, self).__init__()
        self.queue = queue
        self.flag = flag

    def run(self):
        while True:
            try:
                length = len(self.queue)
                print "consumer queue", self.queue
                if length > 5:
                    self.flag.pop()  # 注意我是flag
                    raise ValueError('over')
                self.queue.pop(0)

            except ValueError as e:
                # 通知生产者结束
                # 如何实现?
                print "consumer 我结束了", e
                break
                # raise(e)
            time.sleep(4)

queue = [1, 2, 3]

flag = [0]  # 表示正常

Consumer(queue, flag).start()
time.sleep(1)
Producer(queue, flag).start()

最后说说python的多线程,由于GIL的存在,其实多线程有的时候并不是最好的选择,具体什么时候使用,网上也说的很多了,楼主也可以结合自己的业务情况舍取多线程模块。

PHPzhong

简单的话,就直接把错误raise出来,然后让进程自己崩溃掉就好了.
或者,你也可以用异常处理把消费者的run包裹起来,捕获这个异常,然后再控制生产者的线程就好了.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!