美文网首页
python中的进程+线程

python中的进程+线程

作者: 晨暮云海 | 来源:发表于2017-05-26 10:25 被阅读0次

    以一般程序写法,我定义一个全局变量供进程使用,后来发现,使用不了,原来每个进程占用一块独立的虚拟内存块,我定义的全局变量只是在该进程所占用的内存空间中是全局了,而其他的进程空间是根本看不到这个变量.
    所以网上查了下方法:Python多进程通信Queue、Pipe、Value、Array实例,queue和pipe用来在进程间传递消息、Value + Array 是python中共享内存映射文件的方法.
    然后简易修改代码后:

    # encoding:utf-8
    from multiprocessing import Value,Queue,Process
    import threading
    import time
    
    inq = Queue()
    end = Value('d', 1)
    tend = False
    thds = []
    thd = []
    
    def grap(i):
        #消费者
        try:
            while not tend:
                try:
                    task = inq.get(timeout=0.1)
                except Exception as e:
                    print e
                    break
                print('Worker %s got task %s' % (i, task))
                time.sleep(0)
        except Exception as e:
            print('Quitting time!')
    
    def inpt():
        #生产者
        for i in xrange(100):
            inq.put(i)
            time.sleep(0)
    
    def save(): pass
    
    def is_end():pass
    
    def is_tend():pass
    
    
    def xiancheng():
        global tend
        global thd
        for i in range(10):
            thread = threading.Thread(target=grap, args=(i,))
            thread.daemon = True
            thd.append(thread)
            thread.start()
    
        while not tend:
            tend = is_tend()
            time.sleep(1)
    
    
    if __name__ == '__main__':
        inptthd = Process(target=inpt, args=())
        inptthd.start()
        y = Process(target=save, args=())
        y.start()
        for i in xrange(1):
            p = Process(target=xiancheng, args=())
            thds.append(p)
            p.start()
            print "p.pid:", p.pid
            print "p.name:", p.name
            print "p.is_alive:", p.is_alive()
    
        while 1:
            if is_end():
                end.value = 0
                break
            time.sleep(1)
    

    相关文章

      网友评论

          本文标题:python中的进程+线程

          本文链接:https://www.haomeiwen.com/subject/wgvwxxtx.html