Python中线程池的实现(三)详解编程语言
2023-06-13 09:20:23 时间
# 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!")
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8061.html
cgojavapython相关文章
- python json.loads 中文_Python 的完美 json loads
- python递归函数讲解_Python递归函数实例讲解
- 用几行Python代码实现一个简单的Web服务器详解编程语言
- Python实现的Blowfish加解密详解编程语言
- Python计算文件大小详解编程语言
- python实现一个简单的2048游戏详解编程语言
- Python写计算器详解编程语言
- python通过reportlab实现图片转换pdf详解编程语言
- 用Python实现一个简单的算术游戏详解编程语言
- python实现的堆排序算法代码详解编程语言
- 使用Python 获取文件的MD5详解编程语言
- python实现的telnet客户端程序详解编程语言
- python进阶深入理解系统进程1详解编程语言
- Python学习:1.快速搭建python环境详解编程语言
- python实现快速排序详解编程语言
- python-str字符串详解编程语言
- python实现lower_bound和upper_bound详解编程语言
- python学习Linux、Python,体验自由的乐趣(lexlinux)
- RedMonk公布6月编程语言排行:JavaScript居榜首 Java和Python并列第二
- Python脚本实现Linux系统管理及自动化部署(python写linux)
- Python与MySQL实现数据分析的完美组合(mysql中python)