码迷,mamicode.com
首页 > 编程语言 > 详细

再读《Parallel Programming with Python》并作笔记

时间:2017-10-25 17:12:59      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:技术   rod   utf-8   logger   while   highlight   技术分享   tar   eve   

并发编程,在哪个语言里都属于高端应用,一定得会了才好意思说懂了这门语言。

在工作中用得并不是很多,忘了一些内容,就慢慢看,慢慢补上。

今天一天看了近三分之一(我看外文越来越快了??:)),

实践一下多线程的threading模块。

技术分享

#coding: utf-8

import logging, threading
from Queue import Queue

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(‘%(asctime)s - %(message)s‘)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

fibo_dict = {}
shared_queue = Queue()
input_list = [30, 10, 55, 71]

queue_condition = threading.Condition()

def fibonacci_task(condition):
    with condition:
        while shared_queue.empty():
            logger.info("[%s] - waiting for elements in queue..."
                        % threading.current_thread().name)
            condition.wait()
        else:
            value = shared_queue.get()
            a, b = 0, 1
            for item in range(value):
                a, b = b, a + b
                fibo_dict[value] = a
        shared_queue.task_done()
        logger.debug("[%s] fibonacci of key [%d] with result [%d]" %
                     (threading.current_thread().name, value, fibo_dict[value]))

def queue_task(condition):
    logging.debug(‘Starting queue_task...‘)
    with condition:
        for item in input_list:
            shared_queue.put(item)
        logging.debug("Notifying fibonacci_task threads that the queue is ready to consume...")
        condition.notifyAll()

threads = [threading.Thread(target=fibonacci_task,
                            args=(queue_condition,)) for i in range(4)]
[thread.start() for thread in threads]


prod = threading.Thread(name="queue_task_thread", target=queue_task,
                        args=(queue_condition,))
prod.start()

[thread.join() for thread in threads]

  技术分享

再读《Parallel Programming with Python》并作笔记

标签:技术   rod   utf-8   logger   while   highlight   技术分享   tar   eve   

原文地址:http://www.cnblogs.com/aguncn/p/7729849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!