Python线程问题:线程阻塞每个oth

2024-04-25 17:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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()

此时,工作线程只在启动和退出时打印时间。睡觉双方。问题是,不是得到如下输出:

^{pr2}$

当我做线程.current_线程(),它们都报告自己是主线程。在

就像没有线程,而是在主线程上下文中运行。在

帮忙吗?在

谢谢


Tags: 代码inselftargetforrange线程thread
2条回答

创建Thread对象时,您正在主线程中调用workerFuncSpinner。请改用对方法的引用:

t=threading.Thread(target=self.workerFuncSpinner, 
    args=(taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))

您的原始代码:

^{pr2}$

可以改写为

# 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()

您在主线程中连续调用该方法,而在创建的线程中没有调用任何内容。在

我怀疑你的问题可能是workerFuncSpinner。我将验证它并没有实际运行任务,而是返回一个可调用的对象以供线程运行。在

https://docs.python.org/2/library/threading.html#threading.Thread

相关问题 更多 >