python3 线程池原理_Python中线程池的实现(三)

# -*- coding: utf-8 -*-

# Java 理论与实践: 线程池与工作队列: http://www.ibm.com/developerworks/cn/java/j-jtp0730/

# 线程池原理及python实现: http://www.cnblogs.com/goodhacker/p/3359985.html

# Threadpool: http://chrisarndt.de/projects/threadpool/

# http://www.cnblogs.com/coser/archive/2012/03/10/2389264.html

import Queue

import threading

class ThreadPool(object):

def __init__(self, maxsize=4, timeout=1):

self._maxsize = maxsize

self._timeout = timeout

self._threads = []

self._work_queue = Queue.Queue()

self._create_threads()

def execute(self, func, *args, **kwargs):

self._work_queue.put((func, args, kwargs))

# self._append_thread()

def dismiss(self, do_join=False):

dismiss_list = []

for i in range(len(self._threads)):

thread = self._threads.pop()

thread.dismiss()

dismiss_list.append(thread)

if do_join:

for thread in dismiss_list:

thread.join()

def _create_threads(self):

for i in range(self._maxsize):

self._threads.append(WorkThread(self._work_queue, self._timeout))

# def _append_thread(self):

# num_thread = len(self._threads)

# if num_thread == self._maxsize:

# return

# num_work = self._work_queue.qsize()

# if num_thread >= num_work:

# return

# for i in range(num_thread, min(num_work, self._maxsize)):

# self._threads.append(WorkThread(self._work_queue, self._timeout))

class WorkThread(threading.Thread):

def __init__(self, work_queue, timeout=1):

super(WorkThread, self).__init__()

self._work_queue = work_queue

self._timeout = timeout

self._dismissed = threading.Event()

self.start()

def run(self):

while True:

if self._dismissed.isSet() \

and self._work_queue.qsize() == 0:

break

try:

func, args, kwargs = self._work_queue.get(True, self._timeout)

except Queue.Empty:

continue

else:

func(*args, **kwargs)

# print("%s exited!" % threading.current_thread())

def dismiss(self):

self._dismissed.set()

if __name__ == '__main__':

import time

def do_sth(n):

time.sleep(0.1)

print("task%s in %s" % (n, threading.current_thread()))

pool = ThreadPool()

for i in range(0, 20):

pool.execute(do_sth, i)

pool.dismiss(True)

print("completed!")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值