TypeError:“ bool”对象在创建自定义线程池时不可调用

时间:2019-06-01 17:37:30

标签: multithreading python-3.7

我想创建一个自定义线程池,以便对代码进行更多控制,以满足将来的需求。到目前为止,我还无法编写功能。我希望线程与主解释程序分开工作。我不需要多核优势。 Threads(Worker)应该侦听队列大小的更改并在传递的作业上运行execute。我无法使此代码正常工作。有人看到任何解决方案可以做到这一点吗?

import queue
from threading import Thread
import time
import random

class Worker(Thread):
#----------------------------------------------------------
    def __init__(self,queue,x):
        Thread.__init__(self)
        self.run = True
        self.queue = queue
        self.x = x
#----------------------------------------------------------
    def run(self):
        while self.run:
            while not self.queue.empty():
                job = self.queue.get()
                print("Starting", job, self.x)
                job.executeJob()
                time.sleep(0.1)
                self.queue.task_done()
            time.sleep(0.1)

class TestJob:
    def __init__(self,x):
        self.x = x

    def execute(self):
        print(f"Num {self.x}")

class DownloadManager:
    def __init__(self,numOfThread):
        self.jobQueue = queue.Queue()
        self.numOfThread = numOfThread
        self.threadList = [Worker(self.jobQueue, x) for x in range(0, self.numOfThread)]
        [x.start() for x in self.threadList]
        print("End of init")

    def addJob(self,job):
        self.jobQueue.put(job)

dm = DownloadManager(2)

for x in range(0,10):
    job = TestJob(x)
    dm.addJob(job)

print("After adding all jobs")
input("Waiting for enter")
print("Done")

控制台输出

    Exception in thread Thread-1:
End of init
Traceback (most recent call last):
After adding all jobs
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
TypeError: 'bool' object is not callable

Waiting for enterException in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
TypeError: 'bool' object is not callable



Done

我的Python版本是3.7.2。

1 个答案:

答案 0 :(得分:3)

您的Worker类具有run的2个属性。

class Worker(Thread):
#----------------------------------------------------------
    def __init__(self,queue,x):
        ...
        self.run = True       
        ...
#----------------------------------------------------------
    def run(self):            
        while self.run:
            ...

一个是布尔值(self.run = True),一个是函数(def run(self):)。

You can't have both a method and an attribute with the same name.

根据错误消息,正在调用self.run(),因此run应该是一个函数。尝试将属性self.run更改为其他名称(例如self.is_running)。