• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python 进程 进程池 进程间通信实现解析

python 搞代码 4年前 (2022-01-08) 51次浏览 已收录 0个评论

这篇文章主要介绍了python 进程 进程池 进程间通信实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.python 中创建进程的两种方式:

 from multiprocessing import Process import time def test_(): print '-----test-----' if __name__ == '__main__': p = Process(target=test_) p.start() while True: print '--main--' '''1.通过process 类创建一个进程对象,然后start即可开启进程, test test_函数是进程实现的功能''' from multiprocessing import Process import time class MyNewProcess(Process): def run(self): print '------run-------' if __name__ == '__main__': p = MyNewProcess() p.start() print '---main-----' '''2.通过类似继承process  子类中必须有run 方法 里边实现 进程功能 创建对象之后 调用start'''

2.进程池

 from multiprocessing import Pool from time import sleep import os def func(num): f<mark style="color:transparent">来源gaodaimacom搞#^代%!码&网</mark>or i in range(3): print '%s %s' %(os.getpid(),num) # sleep(2) def main(): pool = Pool(3) for i in range(3, 6): res = pool.apply_async(func, (i,)) pool.close() pool.join() if __name__ == '__main__': main()

3.进程间通信

 '''python 进程间通信   Queue ''' '''1.Queue使用方法 1.Queue.qsize(): 返回当前队列包含的消息数量 2.Queue.empty(): 如果队列为空 返回True 反之 False 3.Queue.full(): 如果队列满了返回True 反之 False 4.Queue.get():  获取队列中一条消息 然后将其从队列中移除 可传参数 超市时长 Queue.get_nowait(): 相当于 Queue.get(False) 取不到值 触发异常 Queue.put(): 将一个值添加到数列 可传参数 超时时长 Queue.put_nowait():相当于 Queue.get(False) 当队列满时 报错 ''' from multiprocessing import Process, Queue import time q = Queue() # 创建队列 for i in range(10): q.put(i) def test_a(): try: while True: num = q.get_nowait() print '我是进程a 取出数字为:%s'%num time.sleep(1) except Exception, e: print e def test_b(): try: while True: num = q.get_nowait() print '我是进程b 取出数字是:%s'%num time.sleep(1) except Exception, e: print e if __name__ == '__main__': p1 = Process(target=test_a) p2 = Process(target=test_b) p1.start() p2.start()

至此 简单得使用已经结束

以上就是python 进程 进程池 进程间通信实现解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python 进程 进程池 进程间通信实现解析
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址