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()
相关推荐
二十七剑19 小时前
LangGraph 源码深度解析:_branch.py 条件分支底层实现原理
python
KaMeidebaby19 小时前
卡梅德生物技术快报|噬菌体展示文库构建全流程解析 | 大豆球蛋白纳米抗体筛选实践
人工智能·python·tcp/ip·算法·机器学习
傻啦嘿哟19 小时前
为什么Python没有块级作用域?
开发语言·python
CC数学建模19 小时前
2026年第十六届APMCM 亚太地区大学生数学建模竞赛(中文赛项)赛题B题:高性能芯片热管理系统的优化问题完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Maydaycxc19 小时前
Python 实现 RPA + AI 自动化:大模型 OCR + 网页操作完整源码实战
人工智能·python·opencv·selenium·自动化·ocr·rpa
stephon_10019 小时前
从零设计 Agent 上下文压缩:三级流水线与动态阈值,治好 context too long(附开源实现)
人工智能·python
love530love19 小时前
Anaconda Navigator 升级后图形界面启动失败故障修复实录
人工智能·windows·python·anaconda·navigator
爱睡懒觉的焦糖玛奇朵19 小时前
【视觉检测之人员奔跑检测算法开发思路】
人工智能·python·深度学习·算法·yolo·视觉检测
装不满的克莱因瓶20 小时前
掌握生成对抗网络(GAN)原理——从零理解“对抗学习”的核心思想与生成机制
人工智能·pytorch·python·深度学习·神经网络·机器学习·ai
王小王-12320 小时前
基于Django的个性化餐饮场所推荐系统
后端·python·django·个性化餐厅推荐·个性化餐饮推荐