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()
相关推荐
前端小趴菜051 小时前
python - 条件判断
python
范男1 小时前
基于Pytochvideo训练自己的的视频分类模型
人工智能·pytorch·python·深度学习·计算机视觉·3d·视频
hui函数1 小时前
Flask-WTF表单验证全攻略
后端·python·flask·web·表单验证
孔丘闻言1 小时前
关于 Flask 3.0+的 框架的一些复习差异点
python·adb·flask
ankleless1 小时前
Python 数据可视化:Matplotlib 与 Seaborn 实战
开发语言·python
witkey_ak98962 小时前
python 可迭代对象相关知识点
开发语言·python
站大爷IP2 小时前
Python生成器与迭代器:从内存优化到协程调度的深度实践
python
二闹3 小时前
Python打印值的两种写法,到底有啥不同?
python
站大爷IP3 小时前
Python构建MCP服务器:从工具封装到AI集成的全流程实践
python
深盾安全5 小时前
Python 装饰器详解
python