簡體   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