传递 kwargs 时的 Python 多处理问题

标签 python threadpool python-multithreading keyword-argument

我试图在类中创建一个线程来启动另一个类构造函数,但似乎 pool.apply_async 没有像我期望的那样传递 kwargs。这是我的代码(精简为仅包含线程代码):

from MyDatabaseScript import DB

class Trinity:
      def __init__(self):

      #lets split a thread off and work on connecting to the mysql server
      pool = ThreadPool(processes=1) #establish the thread pool

      #I want to pass 'self' as an arg to DB because the Trinity instance has class variables that I want to use
      args, kwargs = (self,), {"host":"my.server.name", "user": "databaseuser", "passwd": "xxxxxxxxxxx", "db": "database name"} 

      async_result = pool.apply_async(DB(), args, kwargs) #create the thread pool call for the DB class with the kwargs

现在一切正常,我没有收到任何错误,但在 DB() 方面,我的代码看起来很简单,是这样的:

import MySQLdb

class DB:
      def __init__( self, tms=None, **kwargs ):
          print tms, kwargs

问题是 __init__ 函数中的打印命令不打印任何内容,我明白了:

  None {} 

最佳答案

您正在调用 DB,而不是将 DB 传递给 pool.apply_async

删除():

async_result = pool.apply_async(DB, args, kwargs)

关于传递 kwargs 时的 Python 多处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470476/

相关文章:

python - `with` 中 `concurrent.futures` 的功能

python - 多处理池映射 : AttributeError: Can't pickle local object

python - 通过 '%' 实现 python 字符串操作的多线程安全

指向 SWIG 中 C 结构的 python 指针——访问结构成员

python - 组之间的平衡洗牌

python - 为什么 max() 有时返回 nan 有时忽略它?

java - volatile 变量没有给出预期的输出

java - 创建动态(增长/收缩)线程池

python - 如何在 Panda DataFrame 中拟合预测值

java - 循环方法中的线程