Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2293480
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Python/Ruby

2013-04-23 19:30:52


  1. import time
  2. from multiprocessing import Process,Queue

  3. MSG_QUEUE = Queue(5)

  4. def startA(msgQueue):
  5.     while True:
  6.         if msgQueue.empty() > 0:
  7.             print 'queue is empty %d' % (msgQueue.qsize())
  8.         else:
  9.             msg = msgQueue.get()
  10.             print 'get msg %s' % (msg,)
  11.         time.sleep(1)

  12. def startB(msgQueue):
  13.     while True:
  14.         msgQueue.put('hello world')
  15.         print 'put hello world queue size is %d' % (msgQueue.qsize(),)
  16.         time.sleep(3)

  17. if __name__ == '__main__':
  18.     processA = Process(target=startA,args=(MSG_QUEUE,))
  19.     processB = Process(target=startB,args=(MSG_QUEUE,))

  20.     processA.start()
  21.     print 'processA start..'

  22.     processB.start()
  23.     print 'processB start..'

主进程定义了一个Queue类型的变量,并作为Process的args参数传给子进程processA和processB,两个进程一个向队列中写数据,一个读数据。

其打印的结果如下:

C:\Python27\python.exe E:/outofmemory/test/queuetest/queuetest.py
processA start.. processB start.. queue is empty 0 put hello world queue size is 1 get msg hello world
queue is empty 0 queue is empty 0 put hello world queue size is 1 get msg hello world
queue is empty 0 queue is empty 0 put hello world queue size is 1

转自:
阅读(1096) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~