python循环怎么用python多线程锁的使用去运行

通过线程控制python程序运行一定时间
import time
class Test(threading.Thread):
def __init__(self, para):
#初始化参数
threading.Thread.__init__(self)
self.para= para
def run(self):
while(True):
doMail(self.para)#采集
if __name__ == &__main__&:
while True:
msg = Test(para)
msg.setDaemon(True)
msg.start()
msg.join(2)
time.sleep(2)
上例中,用线程去采集,进程里循环启动线程,每隔2秒,把线程杀死,再重新启动一个新的线程采集
python中得thread的一些机制和C/C++不同:在C/C++中,主线程结束后,其子线程会默认被主线程kill掉。而在python中,主线程结束后,会默认等待子线程结束后,主线程才退出。
python对于thread的管理中有两个函数:join和setDaemon
join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'3119人阅读
Python(5)
原址如下:
春节坐在回家的火车上百无聊赖,偶然看到&&这篇在 Hacker News 和 reddit 上都评论过百的文章,顺手译出,enjoy:-)
Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才是主要问题。常见的经典
Python 多线程、多进程教程多显得偏“重”。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。
简单搜索下“Python 多线程教程”,不难发现几乎所有的教程都给出涉及类和队列的例子:
Standard Producer/Consumer Threading Pattern
import time
import threading
import Queue
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
msg = self._queue.get()
if isinstance(msg, str) and msg == 'quit':
print &I'm a thread, and I received %s!!& % msg
print 'Bye byes!'
def Producer():
queue = Queue.Queue()
worker = Consumer(queue)
worker.start()
start_time = time.time()
while time.time() - start_time & 5:
queue.put('something at %s' % time.time())
time.sleep(1)
queue.put('quit')
worker.join()
if __name__ == '__main__':
Producer()
哈,看起来有些像 Java 不是吗?
我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。
首先,你需要一个样板类;
其次,你需要一个队列来传递对象;
而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。
按照这一思路,你现在需要一个 worker 线程的线程池。下面是中的例子——在进行网页检索时通过多线程进行加速。
A more realistic thread pool example
import time
import threading
import Queue
import urllib2
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
content = self._queue.get()
if isinstance(content, str) and content == 'quit':
response = urllib2.urlopen(content)
print 'Bye byes!'
def Producer():
'http://www.python.org', ''
'http://www.scala.org', ''
queue = Queue.Queue()
worker_threads = build_worker_pool(queue, 4)
start_time = time.time()
for url in urls:
queue.put(url)
for worker in worker_threads:
queue.put('quit')
for worker in worker_threads:
worker.join()
print 'Done! Time taken: {}'.format(time.time() - start_time)
def build_worker_pool(queue, size):
workers = []
for _ in range(size):
worker = Consumer(queue)
worker.start()
workers.append(worker)
return workers
if __name__ == '__main__':
Producer()
这段代码能正确的运行,但仔细看看我们需要做些什么:构造不同的方法、追踪一系列的线程,还有为了解决恼人的死锁问题,我们需要进行一系列的 join 操作。这还只是开始……
至此我们回顾了经典的多线程教程,多少有些空洞不是吗?样板化而且易出错,这样事倍功半的风格显然不那么适合日常使用,好在我们还有更好的方法。
map 这一小巧精致的函数是简捷实现 Python 程序并行化的关键。map 源于 Lisp 这类函数式编程语言。它可以通过一个序列实现两个函数之间的映射。
urls = ['', '']
results = map(urllib2.urlopen, urls)
上面的这两行代码将 urls 这一序列中的每个元素作为参数传递到 urlopen 方法中,并将所有结果保存到 results 这一列表中。其结果大致相当于:
results = []
for url in urls:
results.append(urllib2.urlopen(url))
map 函数一手包办了序列操作、参数传递和结果保存等一系列的操作。
为什么这很重要呢?这是因为借助正确的库,map 可以轻松实现并行化操作。
在 Python 中有个两个库包含了 map 函数: multiprocessing 和它鲜为人知的子库 multiprocessing.dummy.
这里多扯两句: multiprocessing.dummy? mltiprocessing 库的线程版克隆?这是虾米?即便在 multiprocessing 库的官方文档里关于这一子库也只有一句相关描述。而这句描述译成人话基本就是说:&嘛,有这么个东西,你知道就成.&相信我,这个库被严重低估了!
dummy 是 multiprocessing 模块的完整克隆,唯一的不同在于 multiprocessing 作用于进程,而 dummy 模块作用于线程(因此也包括了 Python 所有常见的多线程限制)。
所以替换使用这两个库异常容易。你可以针对 IO 密集型任务和 CPU 密集型任务来选择不同的库。
使用下面的两行代码来引用包含并行化 map 函数的库:
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
实例化 Pool 对象:
pool = ThreadPool()
这条简单的语句替代了 example2.py 中 build_worker_pool 函数 7 行代码的工作。它生成了一系列的 worker 线程并完成初始化工作、将它们储存在变量中以方便访问。
Pool 对象有一些参数,这里我所需要关注的只是它的第一个参数:processes. 这一参数用于设定线程池中的线程数。其默认值为当前机器 CPU 的核数。
一般来说,执行 CPU 密集型任务时,调用越多的核速度就越快。但是当处理网络密集型任务时,事情有有些难以预计了,通过实验来确定线程池的大小才是明智的。
pool = ThreadPool(4)
线程数过多时,切换线程所消耗的时间甚至会超过实际工作时间。对于不同的工作,通过尝试来找到线程池大小的最优值是个不错的主意。
创建好 Pool 对象后,并行化的程序便呼之欲出了。我们来看看改写后的 example2.py
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
'http://www.python.org',
'http://www.python.org/about/',
'/pub/a/python//metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
'http://planet.python.org/',
'https://wiki.python.org/moin/LocalUserGroups',
'http://www.python.org/psf/',
'http://docs.python.org/devguide/',
'http://www.python.org/community/awards/'
pool = ThreadPool(4)
results = pool.map(urllib2.urlopen, urls)
pool.close()
pool.join()
实际起作用的代码只有 4 行,其中只有一行是关键的。map 函数轻而易举的取代了前文中超过 40 行的例子。为了更有趣一些,我统计了不同方法、不同线程池大小的耗时情况。
很棒的结果不是吗?这一结果也说明了为什么要通过实验来确定线程池的大小。在我的机器上当线程池大小大于 9 带来的收益就十分有限了。
生成上千张图片的缩略图
这是一个 CPU 密集型的任务,并且十分适合进行并行化。
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (75,75)
SAVE_DIRECTORY = 'thumbs'
def get_image_paths(folder):
return (os.path.join(folder, f)
for f in os.listdir(folder)
if 'jpeg' in f)
def create_thumbnail(filename):
im = Image.open(filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(filename)
save_path = os.path.join(base, SAVE_DIRECTORY, fname)
im.save(save_path)
if __name__ == '__main__':
folder = os.path.abspath(
'11_18__IQM_Big_Sur_Mon__e10dc3e840')
os.mkdir(os.path.join(folder, SAVE_DIRECTORY))
images = get_image_paths(folder)
for image in images:
create_thumbnail(Image)
上边这段代码的主要工作就是将遍历传入的文件夹中的图片文件,一一生成缩略图,并将这些缩略图保存到特定文件夹中。
这我的机器上,用这一程序处理 6000 张图片需要花费 27.9 秒。
如果我们使用 map 函数来代替 for 循环:
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (75,75)
SAVE_DIRECTORY = 'thumbs'
def get_image_paths(folder):
return (os.path.join(folder, f)
for f in os.listdir(folder)
if 'jpeg' in f)
def create_thumbnail(filename):
im = Image.open(filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(filename)
save_path = os.path.join(base, SAVE_DIRECTORY, fname)
im.save(save_path)
if __name__ == '__main__':
folder = os.path.abspath(
'11_18__IQM_Big_Sur_Mon__e10dc3e840')
os.mkdir(os.path.join(folder, SAVE_DIRECTORY))
images = get_image_paths(folder)
pool = Pool()
pool.map(creat_thumbnail, images)
pool.close()
pool.join()
虽然只改动了几行代码,我们却明显提高了程序的执行速度。在生产环境中,我们可以为 CPU 密集型任务和 IO 密集型任务分别选择多进程和多线程库来进一步提高执行速度——这也是解决死锁问题的良方。此外,由于 map 函数并不支持手动线程管理,反而使得相关的 debug 工作也变得异常简单。
到这里,我们就实现了(基本)通过一行 Python 实现并行化。
译文已获作者 Chris 授权&
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:686856次
积分:9152
积分:9152
排名:第1559名
原创:264篇
转载:155篇
评论:18条
(1)(1)(1)(1)(1)(3)(1)(2)(3)(1)(2)(4)(2)(1)(7)(5)(3)(7)(1)(2)(2)(1)(1)(1)(5)(3)(4)(7)(5)(4)(9)(3)(4)(3)(1)(6)(11)(22)(8)(9)(5)(14)(17)(21)(12)(10)(24)(44)(14)(4)(4)(1)(3)(4)(8)(4)(3)(8)(1)(4)(2)(1)(9)(2)(2)(2)(1)(2)(3)(6)(2)(1)(6)(6)(11)一行 Python 实现并行化 — 日常多线程操作的新思路 - 为程序员服务
一行 Python 实现并行化 — 日常多线程操作的新思路
Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才是主要问题。常见的经典 Python 多线程、多进程教程多显得偏“重”。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。 传统的例子 简单搜索下“Python 多线程教程”,不难发现几乎所有的教程都给出涉及类和队列的例子:#Example.py
Standard Producer/Consumer Threading Pattern
import time
import threading
import Queue
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
# queue.get() blocks the current thread until
# an item is retrieved.
msg = self._queue.get()
# Checks if the current message is
# the "Poison Pill"
if isinstance(msg, str) and msg == 'quit':
# if so, exists the loop
# "Processes" (or in our case, prints) the queue item
print "I'm a thread, and I received %s!!" % msg
# Always be friendly!
print 'Bye byes!'
def Producer():
# Queue is used to share items between
# the threads.
queue = Queue.Queue()
# Create an instance of the worker
worker = Consumer(queue)
# start calls the internal run() method to
# kick off the thread
worker.start()
# variable to keep track of when we started
start_time = time.time()
# While under 5 seconds..
while time.time() - start_time & 5:
# "Produce" a piece of work and stick it in
# the queue for the Consumer to process
queue.put('something at %s' % time.time())
# Sleep a bit just to avoid an absurd number of messages
time.sleep(1)
# This the "poison pill" method of killing a thread.
queue.put('quit')
# wait for the thread to close down
worker.join()
if __name__ == '__main__':
Producer() 哈,看起来有些像 Java 不是吗? 我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。 问题在于… 首先,你需要一个样板类; 其次,你需要一个队列来传递对象; 而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。 worker 越多,问题越多 按照这一思路,你现在需要一个 worker 线程的线程池。下面是中的例子——在进行网页检索时通过多线程进行加速。#Example2.py
A more realistic thread pool example
import time
import threading
import Queue
import urllib2
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
content = self._queue.get()
if isinstance(content, str) and content == 'quit':
response = urllib2.urlopen(content)
print 'Bye byes!'
def Producer():
'http://www.python.org', ''
'http://www.scala.org', ''
queue = Queue.Queue()
worker_threads = build_worker_pool(queue, 4)
start_time = time.time()
# Add the urls to process
for url in urls:
queue.put(url)
# Add the poison pillv
for worker in worker_threads:
queue.put('quit')
for worker in worker_threads:
worker.join()
print 'Done! Time taken: {}'.format(time.time() - start_time)
def build_worker_pool(queue, size):
workers = []
for _ in range(size):
worker = Consumer(queue)
worker.start()
workers.append(worker)
return workers
if __name__ == '__main__':
Producer() 这段代码能正确的运行,但仔细看看我们需要做些什么:构造不同的方法、追踪一系列的线程,还有为了解决恼人的死锁问题,我们需要进行一系列的 join 操作。这还只是开始…… 至此我们回顾了经典的多线程教程,多少有些空洞不是吗?样板化而且易出错,这样事倍功半的风格显然不那么适合日常使用,好在我们还有更好的方法。 何不试试 map map 这一小巧精致的函数是简捷实现 Python 程序并行化的关键。map 源于 Lisp 这类函数式编程语言。它可以通过一个序列实现两个函数之间的映射。urls = ['', '']
results = map(urllib2.urlopen, urls) 上面的这两行代码将 urls 这一序列中的每个元素作为参数传递到 urlopen 方法中,并将所有结果保存到 results 这一列表中。其结果大致相当于:results = []
for url in urls:
results.append(urllib2.urlopen(url)) map 函数一手包办了序列操作、参数传递和结果保存等一系列的操作。 为什么这很重要呢?这是因为借助正确的库,map 可以轻松实现并行化操作。
在 Python 中有个两个库包含了 map 函数: multiprocessing 和它鲜为人知的子库 multiprocessing.dummy. 这里多扯两句: multiprocessing.dummy? mltiprocessing 库的线程版克隆?这是虾米?即便在 multiprocessing 库的官方文档里关于这一子库也只有一句相关描述。而这句描述译成人话基本就是说:”嘛,有这么个东西,你知道就成.”相信我,这个库被严重低估了! dummy 是 multiprocessing 模块的完整克隆,唯一的不同在于 multiprocessing 作用于进程,而 dummy 模块作用于线程(因此也包括了 Python 所有常见的多线程限制)。 所以替换使用这两个库异常容易。你可以针对 IO 密集型任务和 CPU 密集型任务来选择不同的库。 动手尝试 使用下面的两行代码来引用包含并行化 map 函数的库:from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool 实例化 Pool 对象:pool = ThreadPool() 这条简单的语句替代了 example2.py 中 build_worker_pool 函数 7 行代码的工作。它生成了一系列的 worker 线程并完成初始化工作、将它们储存在变量中以方便访问。 Pool 对象有一些参数,这里我所需要关注的只是它的第一个参数:processes. 这一参数用于设定线程池中的线程数。其默认值为当前机器 CPU 的核数。 一般来说,执行 CPU 密集型任务时,调用越多的核速度就越快。但是当处理网络密集型任务时,事情有有些难以预计了,通过实验来确定线程池的大小才是明智的。pool = ThreadPool(4) # Sets the pool size to 4 线程数过多时,切换线程所消耗的时间甚至会超过实际工作时间。对于不同的工作,通过尝试来找到线程池大小的最优值是个不错的主意。 创建好 Pool 对象后,并行化的程序便呼之欲出了。我们来看看改写后的 example2.pyimport urllib2
from multiprocessing.dummy import Pool as ThreadPool
'http://www.python.org',
'http://www.python.org/about/',
'/pub/a/python//metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
'http://planet.python.org/',
'https://wiki.python.org/moin/LocalUserGroups',
'http://www.python.org/psf/',
'http://docs.python.org/devguide/',
'http://www.python.org/community/awards/'
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join() 实际起作用的代码只有 4 行,其中只有一行是关键的。map 函数轻而易举的取代了前文中超过 40 行的例子。为了更有趣一些,我统计了不同方法、不同线程池大小的耗时情况。# results = []
# for url in urls:
result = urllib2.urlopen(url)
results.append(result)
# # ------- VERSUS ------- #
# # ------- 4 Pool ------- #
# pool = ThreadPool(4)
# results = pool.map(urllib2.urlopen, urls)
# # ------- 8 Pool ------- #
# pool = ThreadPool(8)
# results = pool.map(urllib2.urlopen, urls)
# # ------- 13 Pool ------- #
# pool = ThreadPool(13)
# results = pool.map(urllib2.urlopen, urls) 结果:#
Single thread:
14.4 Seconds
3.1 Seconds
1.4 Seconds
1.3 Seconds 很棒的结果不是吗?这一结果也说明了为什么要通过实验来确定线程池的大小。在我的机器上当线程池大小大于 9 带来的收益就十分有限了。 另一个真实的例子 生成上千张图片的缩略图,这是一个 CPU 密集型的任务,并且十分适合进行并行化。 基础单进程版本import os
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (75,75)
SAVE_DIRECTORY = 'thumbs'
def get_image_paths(folder):
return (os.path.join(folder, f)
for f in os.listdir(folder)
if 'jpeg' in f)
def create_thumbnail(filename):
im = Image.open(filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(filename)
save_path = os.path.join(base, SAVE_DIRECTORY, fname)
im.save(save_path)
if __name__ == '__main__':
folder = os.path.abspath(
'11_18__IQM_Big_Sur_Mon__e10dc3e840')
os.mkdir(os.path.join(folder, SAVE_DIRECTORY))
images = get_image_paths(folder)
for image in images:
create_thumbnail(Image) 上边这段代码的主要工作就是将遍历传入的文件夹中的图片文件,一一生成缩略图,并将这些缩略图保存到特定文件夹中。这我的机器上,用这一程序处理 6000 张图片需要花费 27.9 秒。如果我们使用 map 函数来代替 for 循环:import os
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (75,75)
SAVE_DIRECTORY = 'thumbs'
def get_image_paths(folder):
return (os.path.join(folder, f)
for f in os.listdir(folder)
if 'jpeg' in f)
def create_thumbnail(filename):
im = Image.open(filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(filename)
save_path = os.path.join(base, SAVE_DIRECTORY, fname)
im.save(save_path)
if __name__ == '__main__':
folder = os.path.abspath(
'11_18__IQM_Big_Sur_Mon__e10dc3e840')
os.mkdir(os.path.join(folder, SAVE_DIRECTORY))
images = get_image_paths(folder)
pool = Pool()
pool.map(creat_thumbnail, images)
pool.close()
pool.join() 5.6 秒! 虽然只改动了几行代码,我们却明显提高了程序的执行速度。在生产环境中,我们可以为 CPU 密集型任务和 IO 密集型任务分别选择多进程和多线程库来进一步提高执行速度——这也是解决死锁问题的良方。此外,由于 map 函数并不支持手动线程管理,反而使得相关的 debug 工作也变得异常简单。 到这里,我们就实现了(基本)通过一行 Python 实现并行化。 原文出处: 1、下面的网址中可以找到关于 GIL(Global Interpretor Lock,全局解释器锁)更多的讨论: & 2、简言之,IO 密集型任务选择multiprocessing.dummy,CPU 密集型任务选择multiprocessing&
关注Linux运维技术及互联网的IT科技博客
原文地址:, 感谢原作者分享。
您可能感兴趣的代码python线程池(threadpool)模块使用 - jishublog - ITeye技术网站
最近碰到个问题,需要telnet登录上千台机器去取主机名;其中有用户名密码交互部分,有需要延迟的部分,大概一次登录一次到处理完要10s,1000台机器串行处理就需要1000×10s,差不多三个小时,这是很难受的事情;
之前用thread的start_new_thread方法也可以实现,但是线程数量不好控制,没找到相关的控制线程数量的锁;
找了下关于python的线程池,找到threadpool这么一个模块,可以满足我的需求,见:
http://chrisarndt.de/projects/threadpool/
我下的是版本1.2.2:
http://chrisarndt.de/projects/threadpool/download/threadpool-1.2.2.tar.bz2
放到当前目录或者python模块库都行,用法很简单,见:
Basic usage::
&&& pool = ThreadPool(poolsize)
&&& requests = makeRequests(some_callable, list_of_args, callback)
&&& [pool.putRequest(req) for req in requests]
&&& pool.wait()
第一行定义了一个线程池,表示最多可以创建poolsize这么多线程;
第二行是调用makeRequests创建了要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数可以不写,default是无,也就是说makeRequests只需要2个参数就可以运行;
第三行用法比较奇怪,是将所有要运行多线程的请求扔进线程池,[pool.putRequest(req) for req in requests]等同于:
for req in requests:
pool.putRequest(req)
第四行是等待所有的线程完成工作后退出;
下面看下我的代码,使用线程池前后代码对比,不使用线程池:
import telnetlib
import time
#执行比较耗时的函数,需要开启多线程
def myTelnet(L):
tn = telnetlib.Telnet(L[0])
time.sleep(2)
idx = tn.expect(["Username:", "login:"], timeout=5)
time.sleep(3)
x = tn.read_very_eager()
tn.close()
#模拟255个ip,需要逐个登录的函数
def myIpPool(ipPrefix):
for i in range(1, 255):
List.append("%s.%d" % (ipPrefix, i))
return List
#串行运行telnet登录
L=myIpPool("200.200.200")
for i in range(len(L)):
myTelnet(L[i])
如果myTelnet每次执行要10s,那么255次myTelnet就需要2550s,大概是40分钟;
用多线程的情况:
import telnetlib
import time
import threadpool
#执行比较耗时的函数,需要开启多线程
def myTelnet(L):
tn = telnetlib.Telnet(L[0])
time.sleep(2)
idx = tn.expect(["Username:", "login:"], timeout=5)
time.sleep(3)
x = tn.read_very_eager()
tn.close()
#模拟255个ip,需要逐个登录的函数
def myIpPool(ipPrefix):
for i in range(1, 255):
List.append("%s.%d" % (ipPrefix, i))
return List
#使用多线程执行telnet函数
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(myTelnet, L)
[pool.putRequest(req) for req in requests]
pool.wait()
output.close()
开始是个线程,理论上应该快10倍,实际可能没这么快,我将myTelnet函数改成只的sleep 10秒,什么也不干,测了下执行完需要260s,几乎是10倍的速度;改成如下:
pool = threadpool.ThreadPool(30)90s执行完毕,说明线程池还是很有用的东西。
浏览 24016
浏览: 376098 次
怎么下载啊
能识别中文不?
连接时总是报Unable to start Service D ...
如果在社会上,站在政府的立场思考问题,是会被人说5毛的。但是在 ...
我的意思是说,公司采取两种策略:
1. 每月4k的基本工资,另 ...}

我要回帖

更多关于 python多线程锁的使用 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信