【问题标题】:Python threading issue: threads blocking each otherPython线程问题:线程相互阻塞
【发布时间】:2015-04-28 19:39:23
【问题描述】:

我正在尝试在 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() 时,它们都报告说它们是主线程。

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

帮助?

谢谢

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    您在创建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()
    

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

    【讨论】:

    • 就是这样。我不太明白为什么一个 arg 版本假定主线程上下文,但谢谢。
    【解决方案2】:

    我怀疑 workerFuncSpinner 可能是您的问题。我会验证它实际上不是在运行任务,而是返回一个可调用对象以供线程运行。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多