Python 通过threading模块实现多线程
视频版教程 Python3零基础7天入门实战视频教程
我们可以使用threading模块的Thread类的构造器来创建线程
def _ init _(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
上面的构造器涉及如下几个参数。
-
group:指定该线程所属的线程组。目前该参数还未实现,因此它只能设为None。
-
target:指定该线程要调度的目标方法。
-
name:线程名称,一般不用设置
-
args:指定一个元组,以位置参数的形式为 target 指定的函数传入参数。元组的第一个元素传给target函数的第一个参数,元组的第二个元素传给target函数的第二个参数……依此类推。
-
kwargs:指定一个字典,以关键字参数的形式为target 指定的函数传入参数。
-
daemon:指定所构建的线程是否为后代线程。
我们看下实例:
import timedef wishing():while True:print("洗菜菜...啦啦啦")time.sleep(1)def cooking():while True:print("烧饭,烧菜...啦啦啦")time.sleep(1)if __name__ == '__main__':wishing()cooking()
运行输出的,一直是洗菜。
如果我们不用多线程,无法实现两个任务一起执行。
我们使用多线程实现代码:
import threading
import timedef wishing():while True:print("洗菜菜...啦啦啦")time.sleep(1)def cooking():while True:print("煮饭,烧菜...啦啦啦")time.sleep(1)if __name__ == '__main__':# 创建洗菜线程wishing_thread = threading.Thread(target=wishing)# 创建煮饭,烧菜线程cooking_thread = threading.Thread(target=cooking)# 启动线程wishing_thread.start()cooking_thread.start()
传参:
import threading
import timedef wishing(msg):while True:print(msg)time.sleep(1)def cooking(msg):while True:print(msg)time.sleep(1)if __name__ == '__main__':# 创建洗菜线程wishing_thread = threading.Thread(target=wishing, args=("洗菜菜...啦啦啦",))# 创建煮饭,烧菜线程cooking_thread = threading.Thread(target=cooking, kwargs={"msg": "煮饭,烧菜...啦啦啦"})# 启动线程wishing_thread.start()cooking_thread.start()