python - 线程在 python 脚本中不并行运行

标签 python multithreading python-2.7

我是 python 和线程的新手。我试图一次运行多个线程。这是我的基本代码:

  import threading
  import time
  threads = []

  print "hello"

  class myThread(threading.Thread):
          def __init__(self,i):
                  threading.Thread.__init__(self)
                  print "i = ",i
                  for j in range(0,i):
                          print "j = ",j
                          time.sleep(5)

  for i in range(1,4):
          thread = myThread(i)
          thread.start()

当 1 个线程正在等待 time.sleep(5) 时,我希望另一个线程启动。简而言之,所有线程都应该并行运行。

最佳答案

你可能对threading.Thread的子类化有一些误解,首先__init__()方法大致代表了一个构造函数在 Python 中,基本上每次创建实例时它都会执行,所以在 thread = myThread(i) 执行时,它会阻塞直到 __init__() 结束

然后您应该将事件移至 run() ,这样当start()被调用时,线程就会开始运行。例如:

import threading
import time
threads = []

print "hello"

class myThread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.i = i

    def run(self):
        print "i = ", self.i
        for j in range(0, self.i):
            print "j = ",j
            time.sleep(5)

for i in range(1,4):
    thread = myThread(i)
    thread.start()

P.S. 因为GIL的存在在 CPython 中,如果任务受 CPU 限制,您可能无法充分利用所有处理器。

关于python - 线程在 python 脚本中不并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001643/

相关文章:

python - 2.4 和 2.7 之间内置 round() 函数的 Python 变化

python-2.7 - 为什么在Python中从打印中获取无效的语法?

python - 尝试解析嵌入在网页中的列表中的项目

python - 加载改变 sys.path 的模块

c# - 我可以拦截 Task.Factory.StartNew 吗?

c# - 填充多个列表框时创建响应式 WPF UI 的技巧是什么?

python - pandas:基于 NaN 的切片数据帧

python - 我使用的是哪个版本的 python 时间模块

python - 使用 functools partialmethod 定义的函数的文档

Android runOnUiThread - 如何传递 Activity