Python线程问题:线程互相阻塞

时间:2015-04-28 19:39:23

标签: python multithreading

我正在尝试在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()

此时,工作线程仅在启动和退出时打印,并且时间间隔为.sepeps。问题是,而不是输出如下:

#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()时,它们都报告它们是主线程。

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

帮助?

由于

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

我怀疑workerFuncSpinner可能是你的问题。我会验证它实际上没有运行任务,但是返回一个可调用的对象让线程运行。

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

相关问题