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

发布于:2025-08-30 ⋅ 阅读:(22) ⋅ 点赞:(0)

多线程

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()

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完成多进程

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()

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