【问题标题】:Python - Convert threading to Thread pool?Python - 将线程转换为线程池?
【发布时间】: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


【解决方案1】:

Multiprocessing 是一个基于进程的高级并行包。要使用进程,您需要能够在进程之间发送数据,这就是错误消息告诉您的某些数据是不可能的(pickleable = transferable)。但是,如果您在以下位置阅读模块文档:

https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy

你会发现提到了一个叫做 multiprocess.dummy 的东西。导入它,您将使用相同的界面,但使用线程而不是进程。这就是你想要的。

编辑:

花时间阅读多处理模块的规范。您正在做的是将单个线程对象的创建提交到池中。你想要的是提交要完成的工作和要完成工作的项目。 (概念上)正确的解决方案如下所示:

def work(item):
    item = item.strip()
    <actual work that needs to be threaded>

pool = ThreadPool(10)
results = pool.map(work, mylist)
pool.close() # don't think this is strictly necessary

您不向池提交线程,而是将工作交给池中包含的线程。这是一个更高层次的抽象。希望这可以解决问题。

【讨论】:

  • 谢谢,仍然无法正常工作,但至少我没有收到错误消息,脚本只是像过去一样清除,但没有。我的设置方式可能有问题。
  • 把带有池的代码给我们,然后我们就可以看到问题所在了。
  • 有人能帮忙吗?仍然有问题:(
猜你喜欢
  • 1970-01-01
  • 2012-12-28
  • 2010-09-18
  • 1970-01-01
  • 2010-11-24
  • 2012-04-06
  • 2018-09-30
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多