Python + threading对给定序列利用多线程进行求和

本文知识点
1、利用threading模块进行多线程操作
2、根据线程个数进行序列分解

代码如下

import threading

sums = 0

def add(tpl):
    '''This function processes addition operation for given tuple'''
    global sums
    x = tpl[0]
    y = 1+tpl[-1]
    for i in range(x,y):
        sums += i

if __name__ == "__main__":
    n = int(input('Please enter threads number:\n'))  # threads number for addition operation
    start = int(input('Please enter start number of sequence:\n'))  # start number to be added
    end = int(input('Please enter end number of sequence:\n'))  # end number to be added
    # n = 6
    # start = 1
    # end = 100
    while True:
        if n>=end or n <=1:
            print('thread number should be between 2 and end of sequence')
            break
        elif start >= end:
            print('start number should be less than end number')
            break
        else:           
            seq = range(start,end)
            step = len(seq)//n

        # break the given tuple down into a tuple list by thread number
        tpl = []
        tpl1 = (start, start + step)
        tpl.append(tpl1)
        for i in range(2, n):
            temp = (start + (i-1)*step + 1, start + i * step)
            tpl.append(temp)
        tplf = (start + (n-1)*step + 1, end)
        tpl.append(tplf)
        # print(tpl)

        # generate threads to run add function
        thds = []
        for t in tpl:
            thd = threading.Thread(target=add, args=(t,)) # comma after t is necessary
            thd.start()
            thds.append(thd)
            # print(thd.name)
        for thd in thds:
            thd.join()

        # print the total sums of given tuple
        print('The total sum from %d to %d is: %d\n' % (start, end, sums))
        break

代码运行结果
Python + threading对给定序列利用多线程进行求和_第1张图片

参考内容
https://docs.python.org/3.6/library/threading.html

你可能感兴趣的:(python)