python-多线程(笔记)(持续更新)

多线程

python 复制代码
import threading
import time


def sing():
    while True:
        print("sing a song")
        time.sleep(1)

def dance():
    while True:
        print("chang tiao rap")
        time.sleep(1)

if __name__ =='__main__':

  # 此时只能执行一个函数,必须等到该函数执行完才行
    # sing()
    # dance()
 # 改进 同时进行
    tread01=threading.Thread(target=sing)
    tread02=threading.Thread(target=dance)
    tread01.start()
    tread02.start()
python 复制代码
import threading
import time


def sing(msg):
    while True:
        print("sing a song"+msg)
        time.sleep(1)

def dance(msg):
    while True:
        print("chang tiao rap"+msg)
        time.sleep(1)

if __name__ =='__main__':

    # sing()
    # dance()

    tread01=threading.Thread(target=sing,args=("googd",))
    # 把字典的值传进去
    tread02=threading.Thread(target=dance,kwargs={"msg":"good"})
    tread01.start()
    tread02.start()

使用Process完成多进程

python 复制代码
import multiprocessing
import threading
import time


def sing():
    while True:
        print("sing a song")
        time.sleep(1)

def dance(msg):
    while True:
        print("chang tiao rap"+msg)
        time.sleep(1)

if __name__ =='__main__':

    # sing()
    # dance()

    # 不变
    tread01=multiprocessing.Process(target=sing)

    tread02=multiprocessing.Process(target=dance,kwargs={"msg":"good"})
    tread01.start()
    tread02.start()
python 复制代码
import multiprocessing
import threading
import time


def sing():
        print("sing a song")
        yield


if __name__ =='__main__':

    g=sing()
    print(type(sing()))
    print(type(g))

<class 'generator'>
<class 'generator'>

可以把yield类比成一个return

相关推荐
Olamyh几秒前
【 超越 ReAct:手搓 Plan-and-Execute (Planner) Agent】
python·ai
rainbow6889几秒前
C++开源库dxflib解析DXF文件实战
开发语言·c++·开源
deepxuan2 分钟前
Day7--python
开发语言·python
曲幽11 分钟前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
禹凕16 分钟前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov20 分钟前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀20 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
星辰_mya21 分钟前
Es之脑裂
大数据·elasticsearch·搜索引擎
搞科研的小刘选手29 分钟前
【EI稳定检索会议】第七届计算机信息和大数据应用国际学术会议(CIBDA 2026)
大数据·acm·学术会议·计算机工程·计算机信息·大数据应用·信息与技术
蜡笔小马29 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree