美文网首页
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)

相关文章

  • 多线程爬虫之糗事百科(二)

    在python3中,主线程结束,子线程不会结束 在python3中,主进程结束,子进程不会结束 为了能够让主线程回...

  • Python:进程与线程

    什么是进程,什么是线程,进程和线程的关系这里就不说了,直接讲将Python中如何创建多进程与多线程吧。 多进程 U...

  • python爬虫--day06

    进程 进程的概念 python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python...

  • Python札记52_进程和线程2

    在之前的札记Python札记50_进程和线程1中介绍了进程、线程和子进程以及多进程的相关知识,本札记中重点介绍多线...

  • 浅谈python中的多线程和多进程(二)

    原创:hxj7 本文继续分享一个关于python多线程和多进程区别的例子 前文《浅谈python中的多线程和多进程...

  • Python中的线程与进程

    进程会启动一个解释器进程,线程共享一个解释器进程 Python的线程开发 python的线程开发使用标准库thre...

  • 11-9 多线程和多进程

    Python的GIL是针对进程还是线程?  是线程 Python多核cpu可以运行多线程吗? Python线程执行...

  • 一篇文章搞定Python多进程(全)

    1.Python多进程模块 Python中的多进程是通过multiprocessing包来实现的,和多线程的thr...

  • Node.js 笔记02

    一、关于命令 常用命令: ​ 二、进程和线程 请参考python学习笔记中的线程和进程 进程:我们写的代码和程序都...

  • Python实战 - 第7节:多进程爬虫的数据抓取

    笔记 进程与线程的关系 python中可使用multiprocessing来实现多进程from multiproc...

网友评论

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

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