多线程实现生产者消费者模型,以及线程和进程的回顾

dd

 

from multiprocessing import Pool,Queue
import os
import time

from multiprocessing import Process

from threading import Thread


'''
#进程池
def run_proc():
    print(os.getpid())


if __name__ == "__main__":

    p = Pool(20)

    for i in range(10):
        p.apply_async(run_proc)

    print('processing is end...')
    p.close()
    p.join()
'''


'''
#双进程
def run_proc():
    print(os.getpid())

if __name__=="__main__":


    for i in range(5):

        p = Process(target=run_proc())
        p.start()
        print('processing will start...')

        time.sleep(1)
    print(os.getpid())
    print(os.getppid())
    # p.start()
    # p.join()
'''


'''
#双进程间的内存共享
def write(b):
    for i in ['chen','hang','wang','yadan','wust']:
        b.put(i)
        print('put %s to the queue'%i)
        time.sleep(1)

def read(b):

    while True:
        values = b.get()
        print('get %s from the queue'%values)


if __name__=="__main__":

    q = Queue()
    pw = Process(target=write,args=(q,))
    pr = Process(target=read,args=(q,))

    pw.start()
    pr.start()
    pw.join()

    # pr.terminate()
'''


'''
#双线程
def run(i):
    print('%s is running...'%i)

if __name__=="__main__":
    for i in range(5):
        t = Thread(target=run,args=(i,))
        t.start()
        t.join()
'''

'''
#自定义线程类
def bar():
    print('bar..')

class MyThread(Thread):

    def run(self):
        Thread.run(self)                    #调用了父类的run方法
        print('lslsls')                     #如果没有这句,那么本类中的run方法和父类中的run方法一样

t = MyThread(target=bar)
t.start()
t.join()
'''


#生产者和消费者模型:



class Producer(Thread):
    def __init__(self,name,q):
        super(Producer,self).__init__()
        self.__name = name
        self.__q = q

    def run(self):
        while True:
            if self.__q.full():
                time.sleep(1)
            else:
                self.__q.put('baozi')
                # Thread.run()
                print('%s生产一个包子..'%self.__name)


class Consumer(Thread):
    def __init__(self,name,q):
        super(Consumer,self).__init__()
        self.__name = name
        self.__q = q

    def run(self):
        while True:
            if self.__q.empty():
                time.sleep(1)
            else:
                # Thread.run()
                print('%s吃一个包子'%self.__name)


if __name__=="__main__":

    q = Queue(maxsize=20)

    for i in range(5):
        ii = 'chen%d'%i
        p = Producer(ii,q)
        p.start()

    for j in range(10):
        c = Consumer(i,q)
        c.start()

 

 

 

 

 

 

 

 

 

dd

posted @ 2016-08-24 17:34  航飞冲天  阅读(276)  评论(0编辑  收藏  举报