Python 3.x 如何使用线程同时处理python列表中的所有数据?
我有一个字符串列表,用于处理一些数据。 所有字符串的数据处理不会影响其他字符串的结果Python 3.x 如何使用线程同时处理python列表中的所有数据?,python-3.x,multithreading,list,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.
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()
这是以正确的顺序执行的,而不是同时执行的。
如何使用线程实现它,以便同时处理所有数据?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()
如果我不使用.join(),那么在执行过程中会有任何复杂的情况吗?不会,除非您需要所有处理过的数据来进行进一步的处理