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()

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

相关推荐
智者知已应修善业29 分钟前
【给定英文字符串统计最多小写最前输出】2023-2-27
c语言·开发语言·c++·经验分享·笔记·算法
咕白m62531 分钟前
通过 Python 在 PDF 中添加页面
python
wa的一声哭了44 分钟前
Linux服务器配置ssh免密登陆多台服务器、服务器别名配置
linux·运维·服务器·网络·arm开发·python·ssh
我的golang之路果然有问题1 小时前
mac配置 unity+vscode的坑
开发语言·笔记·vscode·macos·unity·游戏引擎
铅笔小新z1 小时前
【C++】从理论到实践:类和对象完全指南(上)
开发语言·c++
rainFFrain1 小时前
qt显示类控件---QCalendarWidget
开发语言·qt
蓁蓁啊2 小时前
ARM交叉编译中编译与链接参数不一致导致的问题
开发语言·arm开发·嵌入式硬件
go_bai2 小时前
Linux-线程
linux·开发语言·c++·经验分享·笔记
咖啡の猫2 小时前
Python中的输出函数
开发语言·数据库·python
zzzsde2 小时前
【C++】二叉搜索树
开发语言·c++