python_day17_多线程

threading模块

python 复制代码
import time


def sing():
    while True:
        print("唱歌~~~~~~~~~~~~")
        time.sleep(1)


def dance():
    while True:
        print("跳舞############")
        time.sleep(1)
if __name__ == '__main__':
    sing()
    dance()

此时为单线程

python 复制代码
import threading
import time


def sing():
    while True:
        print("唱歌~~~~~~~~~~~~")
        time.sleep(1)


def dance():
    while True:
        print("跳舞############")
        time.sleep(1)

if __name__ == '__main__':
    # sing()
    # dance()
    # 多线程
    sing_thread = threading.Thread(target=sing)
    dance_thread = threading.Thread(target=dance)
    sing_thread.start()
    dance_thread.start()

使用threading模块,实现多线程

python 复制代码
import threading
import time


def sing_msg(msg):
    while True:
        print(msg)
        time.sleep(1)


def dance_msg(msg):
    while True:
        print(msg)
        time.sleep(1)

if __name__ == '__main__':
    # 注意此处元组
    sing_msg_thread = threading.Thread(target=sing_msg, args=("唱歌",))
    dance_msg_thread = threading.Thread(target=dance_msg, kwargs={"msg": "跳舞"})
    sing_msg_thread.start()
    dance_msg_thread.start()

元组中仅含一个元素时,需加逗号,多线程传参

相关推荐
景天科技苑21 分钟前
【Rust宏编程】Rust有关宏编程底层原理解析与应用实战
开发语言·后端·rust·rust宏·宏编程·rust宏编程
YBCarry_段松啓1 小时前
uv:下一代 Python 包管理器
人工智能·python
yorushika_1 小时前
python打卡训练营打卡记录day45
开发语言·python·深度学习·tensorboard
封奚泽优1 小时前
使用Python进行函数作画
开发语言·python
fc&&fl1 小时前
大模型面试题总结
人工智能·python
aningxiaoxixi1 小时前
JAVA之 Lambda
java·开发语言
databook1 小时前
稀疏表示与字典学习:让数据“瘦身”的魔法
python·机器学习·scikit-learn
Sheeep1 小时前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
come112342 小时前
Claude 写 PHP 项目的完整小白教程
开发语言·php
虾球xz2 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习