Python多线程求和程序
来源:互联网 发布:阿里云服务器数据恢复 编辑:程序博客网 时间:2024/05/16 08:21
今天写了一个Python的多线程求和程序。满足以下要求:
1、可以设置步长
2、步长可为负
3、支持小数
4、可指定线程数
5、处理各种无效输入
程序如下:
import threadingfrom math import ceilresult = 0def 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 += sumdef 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 resultif __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)
1 1
- Python多线程求和程序
- python多线程端口扫描程序
- Python多线程Socket程序例子
- tensorflow(Python)多线程程序
- LinuxC多线程求和
- python多线程 实现程序快速处理
- python多线程并发执行程序实战讲解
- python 多线程自动刷票程序
- python实现的多线程验证代理程序
- 谈Python多线程及程序锁
- python手动中断多线程程序方法详解
- python聊天程序(socket+多线程)
- python --利用Socket多线程的FTP程序
- 求和程序 继续
- 急需:JAVA求和程序
- 【程序25】阶乘 求和
- C++ 多线程处理求和问题
- 多线程-多线程方式3的求和案例
- 使用ShareSDK手机端和服务器的交互流程图
- Postgresql9.3安装和使用
- 电商双11已臻巅峰,众筹的双11才刚刚开始
- jQuery EasyUI使用教程之创建可折叠面板
- 2015 南阳CCPC hdu5543 Pick The Sticks(01背包)
- Python多线程求和程序
- 关于jQuery对象和DOM对象的区别
- <android5.0>之dialog的使用
- 项目中是否 使用Automatic Reference Counting
- 设计模式 观察者模式 以微信公众服务为例
- 白盒测试的六种覆盖方式
- LITTLE SHOP OF FLOWERS(dp)
- 秒杀系统架构设计
- 设计模式 -- 单例模式(Singleton)