粗谈Python多线程

Python 程序的时候我们也会遇到这种“同时”的需求,同时有大量的请求过来,要我们同时对它们进行处理,那么这个处理的方法,就是「多线程」编程

==GIL(全局解释器锁)==它的作用是避免 Python 解释器中的线程问题,这样造成了在任意时刻只有一个线程在执行 Python 代码

Python_threading.jpg

1、入门级:

import threading

def func(): 
    print('tomorrow advancing technology')
    
def main():    
    for i in range(8): 
        t = threading.Thread(target=func) 
        t.start()

if __name__ == '__main__': 
    main()

2、打印线程运行状态

import threading
import time
from threading 
import current_thread
def func(): 
    print(current_thread().getName(),'start') 
    print('tomorrow advancing technology') 
    time.sleep(1) 
    print(current_thread().getName(), 'end')

def main(): 
    for i in range(4): 
        t = threading.Thread(target=func) 
        t.start()

if __name__ == '__main__': 
    main()

3、多线程传参

import threading 
import time

def func(cnt, name):
    for i in range(cnt):
        print("tomorrow is {} ".format(name))

def main():
    weeks = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fir']
    for i in range(6):
        t = threading.Thread(target=func, args=(5, weeks[i]))
        t.start()

if __name__=='__main__':
    main()
python_thread.jpg

你可能感兴趣的:(粗谈Python多线程)