Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1747331
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2015-09-04 11:25:29

该例子就是parallel_fibonacci.py.
每次跑有时候能获取到一个结果,有时候一个结果也获取不到。

点击(此处)折叠或打开

  1. import logging,threading
  2. import time
  3. from queue import Queue

  4. logger=logging.getLogger()
  5. logger.setLevel(logging.DEBUG)

  6. formatter=logging.Formatter('%(asctime)s-%(message)s')

  7. ch=logging.StreamHandler()
  8. ch.setLevel(logging.DEBUG)
  9. ch.setFormatter(formatter)
  10. logger.addHandler(ch)

  11. fibo_dict={}
  12. shared_queue=Queue()
  13. input_list=[3,10,5,7]

  14. queue_condition=threading.Condition()

  15. def fibonacci_task(condition):
  16.     with condition:
  17.         while shared_queue.empty():
  18.             logger.info("[%s] -waiting for elements in queue..."
  19.                 %threading.current_thread().name)
  20.             condition.wait()
  21.         else:
  22.             value=shared_queue.get()
  23.             a,b=0,1
  24.             for item in range(value):
  25.                 a,b=b,a+b
  26.                 fibo_dict[value]=a
  27.         shared_queue.task_done()
  28.     with condition:
  29.         while shared_queue.empty():
  30.             logger.info("[%s] -waiting for elements in queue..."
  31.                 %threading.current_thread().name)
  32.             condition.wait()
  33.         else:
  34.             value=shared_queue.get()
  35.             a,b=0,1
  36.             for item in range(value):
  37.                 a,b=b,a+b
  38.                 fibo_dict[value]=a
  39.         shared_queue.task_done()
  40.         logger.debug("[%s] fibonacci of key [%d] with result [%d]"
  41.                 %(threading.current_thread().name,value,fibo_dict[value]))

  42. def queue_task(condition):
  43.     logging.debug('Starting queue_task...')
  44.     with condition:
  45.         for item in input_list:
  46.             shared_queue.put(item)
  47.         logging.debug('Notifying fibonacci_task threads\
  48.             that the queue is ready to consume..')
  49.         condition.notifyAll()

  50. threads=[threading.Thread(daemon=True,target=fibonacci_task,
  51.     args=(queue_condition,)) for i in range(4)]

  52. [thread.start() for thread in threads]

  53. prod=threading.Thread(name='queue_task_thread',daemon=True,
  54.     target=queue_task,args=(queue_condition,))
  55. prod.start()
  56. #prod.join()
  57. #time.sleep(10)
  58. [thread.join for thread in threads]
出错的理由如下:
Daemonic threads can’t be joined. However, they are destroyed automatically when the main thread terminates.
把threads 语句中daemon=True 改成了False 就能得到正确的结果



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