【发布时间】:2019-10-17 22:11:07
【问题描述】:
我想创建一个自定义线程池,以便更好地控制代码以满足未来的需求。到目前为止,我还不能写出一些功能性的东西。我希望线程与主解释器进程分开工作。我不需要多核优势。 Threads(Worker) 应该监听队列大小的变化并在传递的作业上运行执行。我无法让这段代码工作。有没有人看到任何解决方案来完成这项工作?
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.execute()
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。
【问题讨论】:
标签: python multithreading typeerror python-3.7