惜风不起、唯有努力!
python 多线程使用

python 多线程使用

在实际的应用场景中,我们都会应用到多线程和多进程,我这篇只讲多线程,多进程下篇输出。直接上源代码如下。

#没多线程之前的调用
import time, threading
start = time.perf_counter()

def threading01(*x):
    for i in x:
        if i > 8:
            print(i)
    time.sleep(5)
threading01(2,4,6,8,10,)

def threading02(**s):
        for h in s:
            if h == "strs":
                print(h)
        time.sleep(5)
threading02(num="100",strs="ftg",name="xiaof")

finish = time.perf_counter()
print(f"全部任务执行完成,耗时 {finish - start} 秒")

#执行结果为10点几秒
#利用多线程调用
import time, threading, os
start = time.perf_counter()
print(f"当前进程pid: {os.getpid()}", f"父进程ppid: {os.getppid()}")

#函数分别接收元组和字典
def threading01(*x):
    print('001线程start')
    for i in x:
        if i > 8:
            print(i)
    time.sleep(5)

def threading02(**s):
        print('002线程start')
        for h in s:
            if h == "strs":
                print(h)
        time.sleep(5)

thread1 = threading.Thread(target=threading01,args=(2,4,6,8,10))   #传入元组
thread2 = threading.Thread(target=threading02,kwargs={"num":100, "strs":"ftg", "name":"xiaof"}) #传入字典


#启动线程
thread1.start()
thread2.start()
#让主线程挂起,等待子线程执行完之后在退出,如果主线程提前退出,子线程也会退出。
thread1.join()
thread2.join()

finish = time.perf_counter()
print(f"全部任务执行完成,耗时 {finish - start} 秒")

#执行结果为5点几秒

普通多线程传参如下

start = time.perf_counter()
print(f"当前进程pid: {os.getpid()}", f"父进程ppid: {os.getppid()}")

def threading01(num, num02=3000):
    print('001线程start')
    print(num, num02)
    time.sleep(5)


def threading02(strs):
        print('002线程start')
        print(strs)
        time.sleep(5)

# threading02(num="100",strs="ftg",name="xiaof")

thread1 = threading.Thread(target=threading01,args=[1000])
thread2 = threading.Thread(target=threading02,args=["两千"])
thread1.start()
thread2.start()
thread1.join()
thread2.join()

finish = time.perf_counter()
print(f"全部任务执行完成,耗时 {finish - start} 秒")

PS: Python的多线程对IO密集型代码要比CPU密集型代码更加友好。

发表回复

您的电子邮箱地址不会被公开。