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()
相关推荐
仙人掌_lz4 小时前
利用python从零实现Byte Pair Encoding(BPE):NLP 中的“变形金刚”
开发语言·python·gpt·自然语言处理·llm·token·deepseek
羊小猪~~4 小时前
深度学习项目--分组卷积与ResNext网络实验探究(pytorch复现)
网络·人工智能·pytorch·python·深度学习·神经网络·机器学习
q567315234 小时前
使用Alamofire下载网站首页内容
开发语言·爬虫·python·scrapy·golang
Aerkui5 小时前
Python标准库-copy
开发语言·python
Try,多训练5 小时前
Pytorch查看神经网络结构和参数量
人工智能·pytorch·python
hweiyu006 小时前
Python从入门到精通全套视频教程免费
开发语言·python
安迪小宝8 小时前
python基础语法10-异常处理
服务器·开发语言·python
Kylin5249 小时前
Java实验二
java·开发语言·python
深度学习lover9 小时前
<数据集>苹果识别数据集<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果识别
DreamNotOver10 小时前
自动提取pdf公式 ➕ 输出 LaTeX
python·pdf·gui·提取公式