python threading 线程池_python 怎样用threading多线程处理同一数据

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)

shared_queue = Queue()

queue_condition = threading.Condition()

queue_lock = threading.Lock()

def print_task(condition):

with condition:

while True:

if shared_queue.empty():

logger.info("[%s] - waiting for elements in queue.." % threading.current_thread().name)

condition.wait()

else:

value = shared_queue.get()

if value > 100:

break

logger.debug("[%s] print [%d]" % (threading.current_thread().name, value))

def print_task_by_lock():

while True:

with queue_lock:

if shared_queue.empty():

logger.info("[%s] - waiting for elements in queue.." % threading.current_thread().name)

else:

value = shared_queue.get()

if value > 100:

break

logger.debug("[%s] print [%d]" % (threading.current_thread().name, value))

def put(condition):

with condition:

for i in range(1, 200):

shared_queue.put(i)

logger.debug("put element [%d] into queue.." % i)

condition.notifyAll()

def put_by_lock():

with queue_lock:

for i in range(1, 200):

shared_queue.put(i)

logger.debug("put element [%d] into queue.." % i)

# producer = threading.Thread(daemon=True, target=put, args=(queue_condition,))

producer = threading.Thread(daemon=True, target=put_by_lock, args=())

producer.start()

# consumers = [threading.Thread(daemon=True, target=print_task, args=(queue_condition,)) for i in range(4)]

consumers = [threading.Thread(daemon=True, target=print_task_by_lock, args=()) for i in range(4)]

[consumer.start() for consumer in consumers]

[consumer.join() for consumer in consumers]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值