企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
[TOC] # multiprocessing 在`multiprocessing`中,通过创建一个`Process`对象然后调用它的`start()`方法来生成进程。`Process`和`threading.Thread`API 相同。 一个简单的多进程程序示例是: ~~~ from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ~~~ # 直接使用Thread创建线程 ~~~python from threading import Thread import threading import os import time import random def not_know(thread_num): print("第%d线程吟唱:不知天上宫阙"%(thread_num)) time.sleep(random.random()) print("第%d线程吟唱:今夕是何年"%(thread_num)) time.sleep(random.random()) print("第%d号线程:<吟唱古诗>任务结束..."%(thread_num)) def main(): for i in range(1, 6): num = len(threading.enumerate()) print("当前线程数为:%d"%num) t = Thread(target=not_know, args=(i,)) t.start() time.sleep(0.8) if __name__ == "__main__": print("--->主函数开始运行<---") main() print("--->主函数运行完毕<---") ~~~ # 定义类继承threading.Thread,然后重写run方法(run方法相当于功能函数) ~~~python from threading import Thread import threading import os import random import time class the_cosmetic(threading.Thread): def __init__(self, num): self.num = num # 一定要记得调用父类构造方法 threading.Thread.__init__(self) def run(self): print("-->第%d线程开始执行<--"%self.num) time.sleep(random.random()) print("%d最有效的化妆品是什么?"%self.num) time.sleep(random.random()) print("%dPhotoshop是最好的化妆品!"%self.num) time.sleep(random.random()) print("-->第%d线程执行完毕<--"%self.num) def main(): print("-------->开始创建线程<--------") for i in range(1, 6): t = the_cosmetic(i) t.start() print("-------->线程创建完毕<--------") if __name__ == "__main__": main() ~~~ # gevent(使用简单,推荐!需要pip安装gevent)~~~python import time import random import gevent from gevent import monkey monkey.patch_all() def peach(name): for i in range(1, 6): start_time = time.time() time.sleep(random.random()) end_time = time.time() # 使用 round() 控制小数点位数! print("%s产出第%s个桃子,耗时%s"%(name, i, round(end_time - start_time, 2))) def apple(name): for i in range(1, 8): start_time = time.time() time.sleep(random.random()) end_time = time.time() print("%s产出第%s个苹果,耗时%s"%(name, i, round(end_time - start_time, 2))) def main(): # 注意:下面的语句,没有等号! 没有等号! 没有等号! gevent.joinall([ gevent.spawn(peach,"LI"), gevent.spawn(apple,"HO"), ]) if __name__ == "__main__": main() ~~~