【发布时间】:2015-01-14 18:17:48
【问题描述】:
我有一个使用线程运行良好的现有脚本,但是我的事情列表越来越大,我需要限制实际使用的线程数,因为我正在杀死我的服务器.. . 所以我想在这个脚本中添加一个 Pool(100) ,但到目前为止我尝试的一切都失败了,并出现了错误代码。任何人都可以帮助添加一个简单的池吗?我一直在环顾四周,很多游泳池都非常复杂,我宁愿让它尽可能简单。请注意我删除了实际的“def work(item)”,因为这个脚本相当大。
import time, os, re, threading, subprocess, sys
mylist = open('list.txt', 'r')
class working (threading.Thread):
def __init__(self, item):
threading.Thread.__init__(self)
self.item = item
def run(self):
work(self.item)
def work(item):
<actual work that needs to be threaded>
threads = []
for l in mylist:
work1 = l.strip()
thread = working(work1)
threads.append(thread)
thread.start()
for t in threads: t.join()
mylist.close()
添加池时出现错误:
Process PoolWorker-10:
Traceback (most recent call last):
File "/usr/lib64/python2.6/multiprocessing/process.py", line 232, in _bootstrap
self.run()
File "/usr/lib64/python2.6/multiprocessing/process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib64/python2.6/multiprocessing/pool.py", line 71, in worker
put((job, i, result))
File "/usr/lib64/python2.6/multiprocessing/queues.py", line 366, in put
return send(obj)
UnpickleableError: Cannot pickle <type 'thread.lock'> objects
刚刚清除的新代码:
import time, os, re, threading, subprocess, sys
from multiprocessing.dummy import Pool as ThreadPool
mylist = open('list.txt', 'r')
class working (threading.Thread):
def __init__(self, item):
threading.Thread.__init__(self)
self.item = item
def run(self):
work(self.item)
def work(item):
<actual work that needs to be threaded>
threads = []
for l in mylist:
work1 = l.strip()
pool = ThreadPool(10)
pool.map(working, work1)
pool.close()
【问题讨论】:
-
回溯似乎与您尝试执行的代码不匹配 - 并且(当您发现困难的方式时),多处理进程的工作方式与线程非常不同,因此只需删除一个替代另一个几乎不会奏效。
标签: python multithreading pool