今天写了一个Python的多线程求和程序。满足以下要求:
1、可以设置步长
2、步长可为负
3、支持小数
4、可指定线程数
5、处理各种无效输入
程序如下:
import threading
from math import ceil
result = 0
def sub_sum(start, end, step):
global result
sum = float(0)
temp = start
while temp < end + step / 1000000:
sum += temp
temp += step
#print("sum from %f to %f by the step %f is %f"\
# % (start, end, step, sum))
result += sum
def thread_sum(start, end, step = 1, num_thread = 1):
global result
num_threads = int(num_thread)
if (num_threads <= 0):
num_threads = 1
end = start + int((end - start)/step) * step
numbers = end - start
if (numbers < 0 and step > 0) or (numbers > 0 and step < 0):
print("error in sum: from %f to %f by the step %f is invalid."\
% (start, end, step))
return 0
elif numbers == 0:
return start
if numbers < 0:
(start, end, step) = (end, start, -step)
numbers *= -1
d = ceil(numbers / num_thread / step) * step
if d < step:
d = step
begin = 0
threads = []
while start + begin * d < end:
threads.append(threading.Thread(target=sub_sum,\
args=(start + d * begin,\
start + d * (begin + 1) - step \
if start + (begin + 1) * d < end else end,\
step)))
begin += 1
print("Actual threads count: %d" % len(threads))
for i in range(len(threads)):
threads[i].start()
for i in range(len(threads)):
threads[i].join()
return result
if __name__ == "__main__":
start = raw_input("Please input the start: ")
end = raw_input("Please input the end: ")
step = raw_input("Please input the step(default 1): ")
start = float(start)
end = float(end)
step = 1 if step == "" else float(step)
num_thread = raw_input("Please input the num of threads: ")
num_thread = int(num_thread)
if num_thread < 0:
print("The num_thread must be positive but not %d" % num_thread)
exit(0)
print("Ths sum is: %f" % thread_sum(start, end, step, num_thread))
s = 0
if start < end and step > 0:
while start <= end:
s += start
start += step
elif start > end and step < 0:
while start >= end:
s += start
start += step
print("normal function: %s" % s)