繁体   English   中英

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

[英]threads not running parallel in python script

我是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子类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()

PS由于CPython中存在GIL ,因此如果任务受CPU约束,您可能无法充分利用所有处理器的优势。

这是一个有关如何基于代码使用线程的示例:

import threading
import time
threads = []

print "hello"

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

for i in range(1,4):
    thread = threading.Thread(target=doWork, args=(i,))
    threads.append(thread)
    thread.start()

# you need to wait for the threads to finish
for thread in threads:
    thread.join()

print "Finished"
import threading
import subprocess


def obj_func(simid):
    simid = simid
    workingdir = './' +str (simid) # the working directory for the simulation
    cmd = './run_delwaq.sh' # cmd is a bash commend to launch the external execution
    subprocess.Popen(cmd, cwd=workingdir).wait()


def example_subprocess_files():
    num_threads = 4
    jobs = []

    # Launch the threads and give them access to the objective function
    for i in range(num_threads):
        workertask = threading.Thread(target=obj_func(i))
        jobs.append(workertask)

    for j in jobs:
        j.start()

    for j in jobs:
        j.join()

    print('All the work finished!')


if __name__ == '__main__':
    example_subprocess_files()

这不适用于我的情况,即该任务不是打印任务而是CPU密集型任务。 该线程被串行排除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM