如何使用线程同时处理python列表的所有数据?

时间:2019-05-21 07:09:28

标签: python-3.x multithreading list

我有一个字符串列表,用于处理某些数据。 所有字符串的数据处理都不会影响其他字符串的结果。

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print ("Starting " + self.name)
      print_time(self.name, self.counter, 5)
      print ("Exiting " + self.name)

def print_time(threadName, delay, counter):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))
      counter -= 1

myList = ['string0', 'string1', 'string2']

def processFunc():
    count = 0
    for data in myList:
        count += 1
        mythread = myThread(count, "Thread-" + str(count), count)
        mythread.start()
        mythread.join()

processFunc()

这是按正确的顺序执行的,而不是同时执行。 如何使用线程来实现它,以便同时处理所有数据?

1 个答案:

答案 0 :(得分:2)

join()等待线程结束,因此您必须在启动所有线程之后再调用。

def processFunc():
    count = 0
    mythreads=[]
    for data in myList:
        count += 1
        mythread = myThread(count, "Thread-" + str(count), count)
        mythread.start()
        mythreads.append(mythread)
    for mythread in mythreads:
        mythread.join()

processFunc()