32.多线程线程

线程之间内存是共享的。

使用threading模块实现多线程编程。

import threading

thread_obj = threading.Thread(group \[, target \[, name\[, args \[, keyargs]]]] )

  • group: 暂时无用,未来功能的预留参数

  • target: 执行的目标任务名,就是函数的名称

  • name: 线程名,一般不用设置

  • args: 以元组的方式给执行任务传参

  • kwargs: 以字典的方式给执行任务传参

启动线程,让线程开始工作

thread_obj.start()

python 复制代码
import time
import threading


def sing():
    while True:
        print("我在唱歌,啦啦啦")
        time.sleep(1)


def dance():
    while True:
        print("我在跳舞,哗哗哗")
        time.sleep(1)


thread1 = threading.Thread(target=sing)
thread2 = threading.Thread(target=dance)
thread1.start()
thread2.start()

给线程传参args

python 复制代码
import time
import threading


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


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


thread1 = threading.Thread(target=sing, args=('我在唱歌...',))
thread2 = threading.Thread(target=dance, args=("我在跳舞...",))
thread1.start()
thread2.start()

给线程传参kwargs

python 复制代码
import time
import threading


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


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


thread1 = threading.Thread(target=sing, kwargs={'msg': '我在唱歌'})
thread2 = threading.Thread(target=dance, kwargs={'msg': '我在跳舞'})
thread1.start()
thread2.start()
相关推荐
zmzb010314 小时前
Python课后习题训练记录Day194
python·opencv·计算机视觉
benchmark_cc14 小时前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_9669496514 小时前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
65岁退休Coder14 小时前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
wdloumiga15 小时前
使用 Construct 3零基础做一些2D小游戏
python·游戏·游戏2d
用户83562907805115 小时前
使用 Python 查找和替换 Word 文档中的文本
后端·python
黑马水牛15 小时前
Carla仿真系列:9_Carla 单目障碍物测距,四种方法原理与实测
经验分享·python·深度学习·计算机视觉·ros·传感器·carla仿真
Python私教16 小时前
多个项目怎么安全合并?适配层、双轨验证与可回滚切换
python·软件架构·系统迁移
船厂电气自动化ai大模型16 小时前
AI大模型与数学第42课:泰勒级数完整展开(神经网络近似核心)
人工智能·python·深度学习·算法·机器学习
刘新洲17 小时前
我以为 AI Agent 只是调模型,直到我亲手补上审批、Outbox 和故障恢复
python·agent·fastapi