唯一应该在你的
if __name__
guard是全局输入的设置和要执行的功能。就是这样。记住,对于多处理,每个新线程都会启动一个全新的解释器,它会重新运行您的文件,但是
__name__
设置为其他值。任何超出警戒范围的操作都将在每个过程中再次执行。
下面是组织此类代码的方法。这是可行的。
import concurrent.futures
from itertools import product
from time import process_time
# This function generates a dictionary with the string as key and a list of its letters as the value
def genDict (in_value):
out_dict = {}
out_dict[in_value] = list(in_value)
return(out_dict)
def main():
# Generate a list of all combinations of three alphabet letter strings
# this is not necesarily a best example for multithreading, but makes the point
# an io example would really accelerate under multithreading
alphabets = ['a', 'b', 'c', 'd', 'e']
listToProcess = [''.join(i) for i in product(alphabets, repeat = 4)]
print('Lenght of List to Process:', len(listToProcess))
# Send the list which is sent to the genDict function multithreaded
t1_start = process_time()
dictResult = {}
with concurrent.futures.ProcessPoolExecutor(4) as executor:
futures = [executor.submit(genDict, elem) for elem in listToProcess]
for future in futures:
dictResult.update(future.result())
t1_stop = process_time()
print('Multithreaded Completion time =', t1_stop-t1_start, 'sec.')
print('\nThis print statement is outside the loop and function but still gets wrapped in')
print('This is the size of the dictionary: ', len(dictResult))
if "__main__" == __name__:
main()