Python 线程问题 : threads blocking each other

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

此时,工作线程仅在启动和退出时以及 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/

相关文章:

multithreading - 如何在 Perl 中使用线程?

java - wait 在对象上调用,而 sleep 在线程上调用

c - 有没有一种程序化的方法来检查堆栈损坏

c++ - std::unique_lock<mutex> 和 conditional_variable cond 的关系

Java线程示例?

python - Django 查询集,小于或大于版本号

python - 使用 python 正则表达式编辑二进制文件/字符串

python - 使用请求获取内容网页

python - 成对嵌套列表的大多数 pythonic(和有效)方式

python - “MySQL 服务器已经消失”,进程持久