1.创建多线程

由于全局解释器锁原因GIL,需要创建一个线程锁

import threading
lock=threading.Lock()    #创建一个线程锁
num=100

def run(name):
    lock.acquire()     #设置线程锁
    global num
    num=num-1
    print("线程",num,"执行了,目前num的值为:",num)
    lock.release()     #释放线程锁

#创建100个线程
for i in range(100):
    t=threading.Thread(target=run,args=(i+1,))
    t.start()

2.创建多进程

from multiprocessing import Process
import time

def run(name):
    print(name,"进程执行了!")
    time.sleep(5)



if __name__ == '__main__':
    #创建线程:
    p1=Process(target=run,args=("p1",))
    p2=Process(target=run,args=("p2",))
    p3=Process(target=run,args=("p3",))
    p4=Process(target=run,args=("p4",))
    p5=Process(target=run,args=("p5",))

    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p5.start()

Comments | NOTHING