我正在尝试在 python 中实现一个简单的线程池。
我使用以下代码启动几个线程:
threads = []
for i in range(10):
t = threading.Thread(target=self.workerFuncSpinner(
taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))
t.setDaemon(True)
threads.append(t)
t.start()
for thread in threads:
thread.join()
此时,工作线程仅在启动和退出时以及 time.sleeps 之间打印。问题是,而不是得到像这样的输出:
#All output at the same time
thread 1 starting
thread 2 starting
thread n starting
# 5 seconds pass
thread 1 exiting
thread 2 exiting
thread n exiting
I get:
thread 1 starting
# 5 seconds pass
thread 1 exiting
thread 2 starting
# 5 seconds pass
thread 2 exiting
thread n starting
# 5 seconds pass
thread n exiting
当我执行 threading.current_thread() 时,它们都报告它们是主线程。
就好像根本没有线程,而是在主线程上下文中运行。
帮忙?
谢谢
最佳答案
创建 Thread
对象时,您正在主线程中调用 workerFuncSpinner
。请改用对该方法的引用:
t=threading.Thread(target=self.workerFuncSpinner,
args=(taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))
您的原始代码:
t = threading.Thread(target=self.workerFuncSpinner(
taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))
t.start()
可以重写为
# call the method in the main thread
spinner = self.workerFuncSpinner(
taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i)
# create a thread that will call whatever `self.workerFuncSpinner` returned,
# with no arguments
t = threading.Thread(target=spinner)
# run whatever workerFuncSpinner returned in background thread
t.start()
您在主线程中串行调用该方法,而在创建的线程中没有任何内容。
关于Python 线程问题 : threads blocking each other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928412/